1. 程式人生 > >vue非父子元件之間傳值

vue非父子元件之間傳值

記錄第一次做專案遇到的坑,可能說的有所欠缺,但是功能是實現的。

為了實現頭部的搜尋框,搜尋table表格中的資料,因為是兩個頁面,所以需要元件傳值。

首先,main.js中建立事件中心eventHub

new Vue({ el: '#app', router, components: { App }, template: '<App/>', // 非父子元件傳遞資料,建立事件中心eventHub data: { eventHub:
new Vue() } })

然後在Header.vue頁面的input輸入框繫結一個變數v-model,點選icon圖示觸發點選事件,methods下的eve()方法傳遞資料

< div class= "head-content-search" > < input type= "text" v-model=" searchKey" class= "username" placeholder
= "請輸入身份證號或姓名" /> < i class= "icon-search" @click=" eve()" ></ i > </ div >


// 非父子元件傳遞資料 eve() { this. $root. eventHub. $emit( 'change', this. searchKey); //eventHub觸發事件
}

最後在home.vue頁面created裡接收資料

// 非父子元件通訊接收資料 this. $root. eventHub. $on( 'change', ( searchKeydata) => { //eventHub接收事件 // 做正則判斷,判斷搜尋框輸入的是身份證或姓名 var reg= / ^ [ \u4e00 - \u9fa5 ] + $ /; if ( reg. test( searchKeydata)) { this. searchKey2 = searchKeydata this. searchKey1 = '' } else { this. searchKey1 = searchKeydata this. searchKey2 = '' } this. getList( 1) });