有没有办法在组件内使用组件时允许事件冒泡?
我的应用程序是一个动态菜单。动态菜单是一个组件 ( dyn-menu
),它为每个 menu-item
使用本地组件 ( <li>
)元素。每个<menu-item>
有一个与之关联的点击处理程序,它发出一个自定义事件(在完整实现中具有菜单项的 ID)。但是应用程序看不到 <menu-item>
发出的事件因为它们没有冒泡。
有没有办法允许 <menu-item>
组件,它是 <dyn-menu>
的本地组件组件,发出事件并仍然允许 vapp
查看和处理事件?
我是 Vuejs 的新手,所以我可能遗漏了一些明显的东西。有可能我试图通过使用两个组件来解决这个问题,但这不是处理它的最佳方式。有没有更好的方法来处理它?</p>
这是一个 jsfiddle .您必须删除 @dyn-menu-item-click='itemClick'
<dyn-menu>
中的行模板来说明如果组件不处理事件,事件不会冒泡。如果删除该行,则 <dyn-menu>
不处理事件但 vapp
也从未看到该事件。
最佳答案
我知道有4个选项
- 像您一样重新发出事件
- 在子组件上(重复地)使用
this.$parent
来访问所需的父组件并发出事件。 (参见下面的“实现您自己的冒泡事件插件”) - 使用由父级
提供
并在子级中注入(inject)
的事件总线。 - 使用 Vuex 存储并将事件推送到子组件中的事件队列。在应用程序的其他地方,观察新元素的 react 事件队列或将其绑定(bind)到某物。
实现自己的冒泡事件插件
非常简单。该插件添加了一个新的 $bubble
方法,该方法向其父级发出冒泡的事件。我考虑过发布一个执行此操作的插件,但它太简单了,开销不值得。
// Add this as a Vue plugin
Vue.use((Vue) => {
Vue.prototype.$bubble = function $bubble(eventName, ...args) {
// Emit the event on all parent components
let component = this;
do {
component.$emit(eventName, ...args);
component = component.$parent;
} while (component);
};
});
// Some nested components as an example
// note usage of "$bubble" instead of "$emit"
Vue.component('component-c', {
template: `
<button type="button" @click="$bubble('my-event', 'payload')">
Emit bubbling event
</button>`,
});
Vue.component('component-b', {
template: `<component-c @my-event="onMyEvent" />`,
methods: {
onMyEvent(...args) {
console.log('component-b listener: ', ...args);
},
},
});
Vue.component('component-a', {
template: `<component-b @my-event="onMyEvent" />`,
methods: {
onMyEvent(...args) {
console.log('component-a listener: ', ...args);
},
},
});
var vapp = new Vue({
el: '#app',
methods: {
onMyEvent(...args) {
console.log('root listener: ', ...args);
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<component-a @my-event="onMyEvent" />
</div>
事件总线
事件总线看起来像这样:
Vue.component('dyn-menu', {
components: {
'menu-item': {
template: '<li @click="itemClick">{{item.text}}</li>',
props: ['item'],
inject: ['eventBus'], // <-- Inject in the child
methods: {
itemClick() {
// Emit the event on the event bus
this.eventBus.$emit('dyn-menu-item-click', ['menu-item dyn-menu-item-click']);
}
}
}
},
// ...
});
var vapp = new Vue({
el: '#app',
data: {
// ...
eventBus: new Vue(),
},
provide() {
return {
// The parent component provides the event bus to its children
eventBus: this.eventBus,
};
},
created() {
// Listen to events on the event bus
this.eventBus.$on('dyn-menu-item-click', this.menuClick);
},
methods: {
menuClick(message) {}
}
})
工作示例:https://jsfiddle.net/7vwfx52b/
此处列出了大量事件总线插件:https://github.com/vuejs/awesome-vue#custom-events
关于javascript - Vuejs - 冒泡自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41993508/