How to create a hook with events between VUE 2.0 components

放肆的年华 提交于 2019-12-12 23:23:06

问题


I've created two dynamic components. Now, using events: $emit/$on what I need is to fire the "logThat(someObj)" method of the component-two passing the arguments as you can see in this fiddle:

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/

If anyone has any suggestions of how to handle this, it will be appreciated :)


回答1:


Technically, you are supposed to use Non-parent-child communication as given in the docs.

But in your current example, it will not work. Reason: Your components 'one' and 'two' are getting created and destroyed as you move back and forth.

Here is your updated jsFiddle: https://jsfiddle.net/mani04/yuh71e1o/4/. Here are the changes:

Event bus:

var bus = new Vue();

Sending event from component-one:

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

Receiving event in component-two:

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

If you open the dev console and observe the logs, you will notice that component-two gets created multiple times and the old ones keep listening as they are not fully destroyed.

To overcome this, you need to move away from dynamic components, and have both your component-one and component-two created at the same time on your root template. You may show / hide based on whichever view you desire, using v-show (not v-if which again destroys the component instance). Then you can use the event bus to communicate, as detailed in the Non-parent-child communication docs.



来源:https://stackoverflow.com/questions/40377977/how-to-create-a-hook-with-events-between-vue-2-0-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!