如何在 VUE 2.0 组件之间创建带有事件的钩子 [英] How to create a hook with events between VUE 2.0 components

查看:21
本文介绍了如何在 VUE 2.0 组件之间创建带有事件的钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个动态组件.现在,使用 事件:$emit/$on我需要的是触发组件的logThat(someObj)"方法——两个传递参数,正如你在这个小提琴中看到的:

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 :)

推荐答案

从技术上讲,您应该使用非亲子通信 如文档中所述.

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.

这是您更新的 jsFiddle:https://jsfiddle.net/mani04/yuh71e1o/4/.以下是变化:

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

事件总线:

var bus = new Vue();

从组件一发送事件:

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

在组件二中接收事件:

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.

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

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.

这篇关于如何在 VUE 2.0 组件之间创建带有事件的钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆