【问题标题】:Root Vue instance not receiving events根 Vue 实例未收到事件
【发布时间】:2019-11-05 04:37:36
【问题描述】:

我无法从根 Vue 实例中的子组件接收任何事件。

我有一个简单的子组件,它在单击或安装时会发出“hello”事件:

<template>
  <div v-on:click="clicked"></div>
</template>

<script>
export default {
  name: 'ChildComponent',
  mounted() {
    this.$emit('hello');
  },
  methods: {
    clicked() {
      this.$emit('hello');
    }
  }
};
</script>

在我的根 Vue 实例中,我已经尝试了一切来接收事件,但似乎没有一个处理程序正在接收事件。我不确定我做错了什么。

const comp = () => import('./components/SomeVueWhichHasChild.vue');

const v = new Vue({
  store,
  render: h => h(comp, {
    on: {
      hello: () => {
        console.log('VUE INSTANCE HELLO');
      }
    },
    nativeOn: {
      hello: () => {
        console.log('NATIVE HELLO');
      }
    }
  }),
});
v.$on('hello', () => {
  console.log('ON HELLO');
});

v.$mount('#app');

【问题讨论】:

  • 您确定调用了子组件中的clicked() 方法吗? div 是空的,所以我认为它没有任何大小;你怎么能点击它?
  • 是的,这只是这篇文章的示例代码。例如,ChildComponent 的父级可以接收事件并将其发送给其父级,依此类推,直到它到达根。就我而言,我正在编写一个插件并且无法控制组件的层次结构。我需要从我的插件组件向根 Vue 实例发出一个事件。到目前为止,我提供的答案对我来说效果很好。

标签: vue.js


【解决方案1】:

似乎这是一个副本:

How to bubble events on a component subcomponent chain with Vue js 2?

只有组件的直接父级可以监听事件。我改用原生 JS 事件:

this.$el.dispatchEvent(new CustomEvent('hello', {
  detail: { ... },
  bubbles: true,
  composed: true
}));

【讨论】:

    【解决方案2】:

    正如@Decade Moon 所说,您的 div 应该有一些可以点击的内容。例如:

    <div v-on:click="clicked">Test content</div>
    

    你可以在Codepen查看我的演示

    【讨论】:

    • 对不起,我的问题不清楚。您的示例有效,因为您的 ChildComponent 是根 Vue 实例的直接子级。在我的示例中,根 Vue 实例的子节点是“SomeVueWhichHasChild”,它可能有 ChildComponent 嵌套 N 层深。
    猜你喜欢
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 2018-06-23
    • 2019-12-22
    • 2016-11-02
    相关资源
    最近更新 更多