Init.Sun Chengdu.Sichuan

通过bus进行组件通信

2017-09-25
Init
vue

vue中组件的通信:props bus vuex …

兄弟通信

非父子组件的通信

// bus.js
import Vue from 'vue';  
export default new Vue();  
// b1.vue
// 触发组件 b2 中的事件
bus.$emit('id-selected', 1)

// b2.vue
// 在组件 b2 创建的钩子(created)中监听事件
bus.$on('id-selected', function (id) {
  // ...
})

父子通信

自定义事件

//父子通信用props,子父通信用自定义事件


<div id="counter-event-example">
  <p></p>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>
</div>


Vue.component('button-counter', {
  template: '<button v-on:click="incrementCounter"></button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    incrementCounter: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})

原理:通过一个空的vue对象,来监听和发送自定义事件。

还有一个办法

使用引用对象。

在复杂的情况下,我们应该考虑使用专门的状态管理模式(vuex)。


Comments