vue中eventBus使用及注意事项

一、eventBus用途:用于解决:一个页面调用另一个页面中的方法。

二.、eventBus使用方法:分为三步骤,如A页面调用B页面中的方法。

  1. 在main.js中将eventBus挂载到vue原型上
    Vue.prototype.$eventBus = new Vue()
  2. 在A页面点击按钮后执行
    <button @goDY()>执行</button>
    
    goDY(){
        let data = {
             a :1
        }
      this.$eventBus.$emit("getData",data)
    }
  3. 在B页面mounted中监听
    mounted(){
    var that = this;
    this.$eventBus.$off("getData")
    this.$eventBus.$on("getData",function(data){
    console.log('监听到变化',data)
    // 开始调用方法
    that.getList(data)
      })
    },
    methods:{
    getList(data){
    console.log('我就是B页面的方法,你已经调用我了')
    }
    }

三、eventBus使用注意事项: 在$on绑定事件之前先使用$off解绑事项。

若不使用  this.$eventBus.$off("getData") 则页面重新进入时,或造成内存泄漏,可以看到重新进入3次后,执行 this.$eventBus.$emit()该方法是,$on会多次绑定,重复监听3次,所以在每次$on接收到事件之前先解绑事件($off)

原文地址:https://www.cnblogs.com/evident/p/15715753.html