要使用 eventBus 在 A 页面和 B 页面之间进行数据通信,可以按照以下步骤进行操作:

  1. 在 main.js 中引入 eventBus,并将其挂载到 Vue 的原型上:
import Vue from 'vue'
import App from './App.vue'

// 创建一个 eventBus 实例
const eventBus = new Vue()

// 将 eventBus 挂载到 Vue 原型上
Vue.prototype.$eventBus = eventBus

new Vue({
  render: h => h(App),
}).$mount('#app')
  1. 在 A 页面中监听 B 页面修改的事件,当事件触发时,更新 A 页面的数据:
export default {
  data() {
    return {
      dataFromBackend: null
    }
  },
  mounted() {
    // 监听 B 页面修改的事件
    this.$eventBus.$on('dataChanged', (newData) => {
      this.dataFromBackend = newData
    })
  }
}
  1. 在 B 页面中修改数据并触发事件:
export default {
  methods: {
    modifyData() {
      // 修改数据
      const newData = 'new data'

      // 触发事件,将修改后的数据传递给 A 页面
      this.$eventBus.$emit('dataChanged', newData)
    }
  }
}

这样,当 B 页面修改数据并触发事件时,A 页面会接收到事件并更新数据,从而实现了 A 页面的重新渲染。


原文地址: https://www.cveoy.top/t/topic/fUzQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录