在组件中使用组件时,是否有方法允许事件冒泡?

我的应用程序是一个动态菜单.动态菜单是一个组件(dyn-menu),它为<li>个元素中的每一个使用一个本地组件(menu-item).每个<menu-item>都有一个与之关联的click处理程序,该处理程序会发出一个自定义事件(在完整实现中具有菜单项的ID).但是应用程序没有看到<menu-item>发出的事件,因为它们没有冒泡.

允许本地组件发出事件的方式<dyn-menu>和允许本地组件发出事件的方式<menu-item>

我是Vuejs的新手,所以我可能错过了一些明显的东西.我可能正试图通过使用两个组件来解决这个问题,但这并不是最好的解决方法.有没有更好的方法?

这是jsfiddle美元.您必须删除<dyn-menu>模板中的@dyn-menu-item-click='itemClick'行,以说明如果组件不处理事件,事件不会冒泡.如果删除该行,则<dyn-menu>不会处理该事件,但vapp也不会看到该事件.

推荐答案

我知道有4种 Select

  1. 像你一样重新emits 事件
  2. 在子组件上使用this.$parent(重复)来访问所需的父组件并发出事件.(请参阅下面的"实现自己的冒泡事件插件")
  3. 使用一个事件总线,该总线由父级执行provided,子级执行injectD.
  4. 使用Vuex存储并将事件推送到子组件中的事件队列.在应用程序的其他地方,观察react 性事件队列中的新元素,或者只是将其绑定到某个东西上.

Implement your own bubbling event plugin

这很简单.该插件添加了一个新的$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>

Event bus

事件总线如下所示:

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

Vue.js相关问答推荐

无法从CDN使用Vue和PrimeVue呈现DataTable

Vuetify 2中自定义标头的排序和筛选

vue3 输入标签给出错误 Vue.use 不是函数

:deep() 带有嵌套 scss 规则的语法

Vuetify/Nuxt 生产环境组件在开发环境中无法正常工作

vue router/:param 斜杠的参数

在 VueJS 中为 Get、Post、Patch 配置全局标头的最佳方法

在组件之间共享 websocket 连接

如何 for each 用户分组聊天消息?

我是否必须在 Vue 3 中使用 Composition API,还是仍然可以使用Vue 2的方式工作?

自定义props类型

vuejs中通过变量动态调用方法

Vuejs模板继承

取消选中单选按钮

vue 3 使用 Vuex 和路由的服务器端渲染

Vue在按钮单击时添加一个组件

使计算的 Vue 属性依赖于当前时间?

Vue Cli 3:定义的输出路径

用于 nuxt.js 构建的自定义 index.html

Vue.js 显示空格(换行符)