组件之间通讯

1.父子之间通讯

父组件传值给子组件,通过props属性的传递,子组件通过$emit事件的触发。

2.自定义事件,非父子组件传值,比如此处是兄弟组件传值

input组件里,触发:

event.js:    event是一个vue实例。

list组件里调用:mounted钩子函数里调用,beforeDestory里销毁。

3.中央总线bus传值

在utils里新建一个eventBus.js文件

const install = (Vue) => {
  const Bus = new Vue({
    methods: {
      emit(event, ...args) {
        this.$emit(event, ...args);
      },
      on(event, callback) {
        this.$on(event, callback);
      },
      off(event, callback) {
        this.$off(event, callback);
      },
    },
  });
  Vue.prototype.$bus = Bus;
};
export default install;

在main.js中引用

import VueBus from './utils/eventBus';
Vue.use(VueBus);

在组件xingyezilvtqcjiancha.vue中触发

sendMsg() {
      let sendMsgInfo = JSON.parse(window.localStorage.getItem('sendMsgInfo'));
      $http.post('/sdkseaunion/portalApi/sendSmsMes', {
        sendPhone: sendMsgInfo.lianxidianhua,
        sendName: sendMsgInfo.displayValue,
        owner: sendMsgInfo.owner,
        shipName: localStorage.getItem('shipName'),
      })
        .then((rspData) => {
          this.$message({
            type: 'success',
            message: '短信发送成功!'
          });
          this.$bus.emit('refreshData');
          destroyAllDialogs();
        }).catch((error) => {
          console.log(error);
        });
    },

在shipInfo.vue中引用

created() {
   this.$bus.on('refreshData', () => { 
      this.queryTabList();
      this.queryTabContent();
   });
   setInterval(this.showMarquee, 3000);
},
beforeDestroy () {
    this.$bus.off('refreshData');
},
原文地址:https://www.cnblogs.com/guwufeiyang/p/13155254.html