如何在VUE 2.0组件之间创建带有事件的钩子

How to create a hook with events between VUE 2.0 components

本文关键字:事件 创建 之间 VUE 组件      更新时间:2023-09-26

创建了两个动态组件。现在,使用事件:$emit/$on我需要的是触发组件的"logThat(someObj)"方法-传递参数,正如您在此页面中看到的:

Vue.component('component-one', {
    template: '#template-a',
    methods: {
        onClick() {
            const someObj = {
                foo: "foo",
                bar: "bar"
            }
            vm.$emit('selected', someObj)
            vm.currentView ='component-two';
        }
    }
});
//Any hint??
/*vm.$on('selected', (someObj) => {
    this.logThat(someObj)
})*/
Vue.component('component-two', {
    template: '#template-b',
    methods: {
        onClick() {
            vm.currentView ='component-one';
        },
        logThat(someObj) {
            console.log(someObj);
       }
    }
});
https://jsfiddle.net/wanxe/yuh71e1o/

如果有人对如何处理这个问题有任何建议,我将不胜感激:)

从技术上讲,您应该使用文档中给出的非父子通信。

但是在您当前的示例中,它将不起作用。原因:当你来回移动时,你的组件"一"answers"二"正在被创建和销毁。

这是你更新的jsFiddle: https://jsfiddle.net/mani04/yuh71e1o/4/。修改如下:

事件总线:

var bus = new Vue();

从组件1发送事件:

bus.$emit('selected', someObj);

组件二接收事件:

created: function() {
   console.log("Created component-two, listening for 'selected' event");
   bus.$on('selected', this.logThat);
}

如果您打开开发控制台并观察日志,您将注意到组件2被创建了多次,而旧的组件继续侦听,因为它们没有完全销毁。

要克服这个问题,您需要远离动态组件,并在根模板上同时创建component-onecomponent-two。您可以根据您想要的视图显示/隐藏,使用v-show(而不是v-if,它再次破坏组件实例)。然后,您可以使用事件总线进行通信,详见非父子通信文档。