How to create a hook with events between VUE 2.0 c

2019-07-28 23:56发布

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条回答
Luminary・发光体
2楼-- · 2019-07-29 00:35

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.

查看更多
登录 后发表回答