天天看點

vue元件間通信vue 8種正常通信方案

vue 8種正常通信方案

1. 通過 props 傳遞
 2. 通過 $emit 觸發自定義事件
 3. 使用 ref
 4. EventBus
 5. $parent 或$root
 6. attrs 與 listeners
 7. Provide 與 Inject
 8. Vuex
           

1 props

适用場景:父元件傳遞資料給子元件

子元件設定

props

屬性,定義接收父元件傳遞過來的參數

父元件在使用子元件标簽中通過字面量來傳遞值

父–>子

//父
<Children name="jack" age=18 />  
//子
props:{  
    // 字元串形式  
 name:String // 接收的類型參數  
    // 對象形式  
    age:{    
        type:Number, // 接收的類型為數值  
        defaule:18,  // 預設值為18  
       require:true // age屬性必須傳遞  
    }  
}  
           

2 $emit 觸發自定義事件

适用場景:子元件傳遞資料給父元件

子元件通過

$emit

觸發自定義事件,

$emit

第二個參數為傳遞的數值

父元件綁定監聽器擷取到子元件傳遞過來的參數

子–>父

// 子
this.$emit('add', good)
//父
<Children @add="cartAdd($event)" />  
           

3 ref

父元件在使用子元件的時候設定

ref

父元件通過設定子元件

ref

來擷取資料

<Children ref="foo" />  
this.$refs.foo  // 擷取子元件執行個體,通過子元件執行個體我們就能拿到對應的資料  
           

4 EventBus

使用場景:兄弟元件傳值

建立一個中央事件總線

EventBus

兄弟元件通過

$emit

觸發自定義事件,

$emit

第二個參數為傳遞的數值

另一個兄弟元件通過

$on

監聽自定義事件

// 建立一個中央時間總線類  
class Bus {  
  constructor() {  
    this.callbacks = {};   // 存放事件的名字  
  }  
  $on(name, fn) {  
    this.callbacks[name] = this.callbacks[name] || [];  
    this.callbacks[name].push(fn);  
  }  
  $emit(name, args) {  
    if (this.callbacks[name]) {  
      this.callbacks[name].forEach((cb) => cb(args));  
    }  
  }  
}  
  
// main.js  
Vue.prototype.$bus = new Bus() // 将$bus挂載到vue執行個體的原型上  
// 另一種方式  
Vue.prototype.$bus = new Vue() // Vue已經實作了Bus的功能
           

子1

子2

5 $parent 或 $root

//通過共同祖輩$parent或者$root搭建通信橋連

//兄弟元件
this.$parent.on('add',this.add)

//另一個兄弟元件
this.$parent.emit('add')
           

6 $attrs 與 $listeners

适用場景:祖先傳遞資料給子孫

設定批量向下傳屬性

$attrs

$listeners

包含了父級作用域中不作為 prop 被識别 (且擷取) 的特性綁定 ( class 和 style 除外)。

可以通過 v-bind=“$attrs” 傳⼊内部元件

// child:并未在props中聲明foo  
<p>{{$attrs.foo}}</p>  
  
// parent  
<HelloWorld foo="foo"/>  
           
// 給Grandson隔代傳值,communication/index.vue  
<Child2 msg="lalala" @some-event="onSomeEvent"></Child2>  
  
// Child2做展開  
<Grandson v-bind="$attrs" v-on="$listeners"></Grandson>  
  
// Grandson使⽤  
<div @click="$emit('some-event', 'msg from grandson')">  
{{msg}}  
</div>  
           

7 provide 與 inject

在祖先元件定義provide屬性,傳回傳遞的值

在後代元件通過inject接收元件傳遞過來的值

祖先

provide(){  
    return {  
        foo:'foo'  
    }  
}  
           

後代

8 vuex

适用場景: 複雜關系的元件資料傳遞

Vuex作用相當于一個用來存儲共享變量的容器

state用來存放共享變量的地方

getter,可以增加一個getter派生狀态,(相當于store中的計算屬性),用來獲得共享變量的值

mutations用來存放修改state的方法。

actions也是用來存放修改state的方法,不過action是在mutations的基礎上進行。常用來做一些異步操作

總結

  • 父子關系的元件資料傳遞選擇

    props

    $emit

    進行傳遞,也可選擇ref
  • 兄弟關系的元件資料傳遞可選擇

    $bus

    ,其次可以選擇

    $parent

    進行傳遞
  • 祖先與後代元件資料傳遞可選擇

    attrs

    listeners

    或者

    Provide

    Inject

  • 複雜關系的元件資料傳遞可以通過

    vuex

    存放共享的變量

繼續閱讀