1.将bus注入到Vue根对象中

const bus = new Vue();
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App },
  data:{
    bus
  } 
});

2.组件A中触发事件

this.$root.bus.$emit('busevent', 19);

3.组件B中监听事件

data () {
    return {
      valNow:''
    }
},
mounted(){
    let nowThis=this;      
    this.$root.bus.$on('busevent',function(val){       //此处this和当前this不同,所以在外部定义变量,以引用当前组件的this
        alert(val);
        nowThis.valNow=val;
    })
}
作者 铁血 汉子 2018年3月16日
2024/04/24/11:57:54pm 2018/3/16/2:04:43
0 2907