vue2.0父子組件以及非父子組件通信


官網API: https://cn.vuejs.org/v2/guide/components.html#Prop

一、父子組件通信

1、父組件傳遞數據給子組件,使用props屬性來實現

  • 傳遞普通字符串

父組件:

<child message="hello!"></child>

子組件:

Vue.component('child', {
    // 聲明 props
    props: ['message'],
    // 就像 data 一樣,prop 也可以在模板中使用
    // 同樣也可以在 vm 實例中通過 this.message 來使用
    template: '<span>{{ message }}</span>'
})

結果:

hello!

 

  • 動態:父組件數據如何傳遞給子組件

父組件:

<child :my-message="parentMsg"></child>

data(){
    return {
        parentMsg: [1,2,3,4,5]
    };
}

子組件:通過props屬性接收數據

// 方式一
props: ['myMessage']

// 方式二
props: {
    myMessage: Array  //指定傳入的類型,如果類型不對,會警告
}

// 方式三
props: {
    myMessage: {
        type: Array,
        default: [5,6,7]  //指定默認的值
    }
}

props屬性驗證有以下形式:

Vue.component('example', {
  props: {
    // 基礎類型檢測 (`null` 指允許任何類型)
    propA: Number,
    // 可能是多種類型
    propB: [String, Number],
    // 必傳且是字符串
    propC: {
      type: String,
      required: true
    },
    // 數值且有默認值
    propD: {
      type: Number,
      default: 100
    },
    // 數組/對象的默認值應當由一個工廠函數返回
    propE: {
      type: Object,
      default: function () {
        return { message: 'hello' }
      }
    },
    // 自定義驗證函數
    propF: {
      validator: function (value) {
        return value > 10
      }
    }
  }
})

2、子組件與父組件通信

vue是單向數據傳遞的,如果子組件直接改變父組件傳過來的數據是不允許的。但是可以通過觸發事件通知父組件改變數據,實現改變子組件的目的。

子組件:

<div @click="childClick()"></div>

methods: {
    childClick() {
        this.$emit('tell','hello'); //主動觸發tell方法,'hello'為向父組件傳遞的數據
    }
}

父組件:

 <child @tell="change" :msg="msg"></child> //監聽子組件觸發的tell事件,然后調用change方法;msg是父組件傳給組件的數據

methods: {
    change(msg) {
        this.msg = msg;
    }
}

 

二、非父子組件通信

有時候,非父子關系的兩個組件之間也需要通信。在簡單的場景下,可以使用一個空的 Vue 實例作為事件總線。原理就是把 Vue 實例當作一個中轉站。

var bus = new Vue();  // 創建事件中心
// 觸發組件 A 中的事件
<div @click="eve"></div>
methods: {
    eve() {
        bus.$emit('change','hehe'); //bus觸發事件
    }
}
// 在組件 B 創建的鈎子中監聽事件
<div></div>
created() {
    bus.$on('change', () => {   // bus接收事件
        this.msg = 'hehe';
    });
}

方法2:

在初始化web app的時候,main.js給data添加一個 名字為eventhub 的空vue對象。就可以使用 this.$root.eventHub 獲取對象。

new Vue({
    el: '#app',
    router,
    render: h => h(App),
    data: {
        eventHub: new Vue()
    }
})

在組件內調用事件觸發

//通過this.$root.eventHub獲取此對象
//調用$emit 方法
this.$root.eventHub.$emit('eventName', data)

在另一個組件調用事件接受,移除事件監聽器使用$off方法。

this.$root.eventHub.$on('eventName', (data)=>{
    // 處理數據
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM