vue 事件总线(bus)

1.全局引入bus

Vue.prototype.$bus = new.Vue()

2.组件间传值使用(在发送事件时接收组件会实时接收到, 可以用做兄弟组件间相互传值, 但页面跳转组件间有问题 通过$emit发送,$on接收)

<div style="float: left; width: 15%; height: 100%;">
         <div v-for="(item, index) in list" 
                 :key="index" 
               @click="okClick(item)">{{item.name}}</div>
</div>

methods: {
      okClick (item) {
          this.$bus.$emit('busClick', item.id)
      }
  },
 mounted() {
            console.log('123')
            this.$bus.$on('busClick', item => {
               switch (item) {
                   case '看下值过来没' :
                       this.items = '看下值过来没'
                       break
                   case 1 :
                       this.items = 1
                       break
                   case 2 :
                       this.items = 2
                       break
               }
            })
        },

3.再接收组件销毁时要把事件清除掉,不然会重复发送和接收

beforeDestroy() {
  this.$bus.$off()
}

  

猜你喜欢

转载自www.cnblogs.com/wjsy/p/12377182.html