如何在 VUE 2.0 组件之间创建事件挂钩
How to create a hook with events between VUE 2.0 components
我创建了两个 dynamic components. Now, using events: $emit/$on
我需要的是触发组件的 "logThat(someObj)" 方法 - 传递参数 正如你在这个 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/
如果有人对如何处理此问题有任何建议,我们将不胜感激:)
从技术上讲,您应该按照文档中的说明使用 Non-parent-child communication。
但在您当前的示例中,它不起作用。原因:您的组件 'one' 和 'two' 在您来回移动时被创建和销毁。
这是您更新的 jsFiddle:https://jsfiddle.net/mani04/yuh71e1o/4/。以下是更改:
事件总线:
var bus = new Vue();
正在从组件一发送事件:
bus.$emit('selected', someObj);
组件二中接收事件:
created: function() {
console.log("Created component-two, listening for 'selected' event");
bus.$on('selected', this.logThat);
}
如果你打开开发控制台并观察日志,你会注意到组件二被创建了多次,旧的组件一直在监听,因为它们没有被完全销毁。
为了克服这个问题,您需要远离动态组件,并在根模板上同时创建 component-one
和 component-two
。您可以根据您想要的任何视图显示/隐藏,使用 v-show
(而不是 v-if
再次破坏组件实例)。然后就可以使用事件总线进行通信了,详见Non-parent-child communication docs.
我创建了两个 dynamic components. Now, using events: $emit/$on 我需要的是触发组件的 "logThat(someObj)" 方法 - 传递参数 正如你在这个 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/
如果有人对如何处理此问题有任何建议,我们将不胜感激:)
从技术上讲,您应该按照文档中的说明使用 Non-parent-child communication。
但在您当前的示例中,它不起作用。原因:您的组件 'one' 和 'two' 在您来回移动时被创建和销毁。
这是您更新的 jsFiddle:https://jsfiddle.net/mani04/yuh71e1o/4/。以下是更改:
事件总线:
var bus = new Vue();
正在从组件一发送事件:
bus.$emit('selected', someObj);
组件二中接收事件:
created: function() {
console.log("Created component-two, listening for 'selected' event");
bus.$on('selected', this.logThat);
}
如果你打开开发控制台并观察日志,你会注意到组件二被创建了多次,旧的组件一直在监听,因为它们没有被完全销毁。
为了克服这个问题,您需要远离动态组件,并在根模板上同时创建 component-one
和 component-two
。您可以根据您想要的任何视图显示/隐藏,使用 v-show
(而不是 v-if
再次破坏组件实例)。然后就可以使用事件总线进行通信了,详见Non-parent-child communication docs.