I've been through the vue.js events section on events but it seems to only give examples of how to listen to events using the vm.$on handler within html. Between that and the new changes for 2.0 I'm unsure how to simply transmit a event from child -> parent.

我需要传输一个事件,因为在父母接收后,我想把它广播给另一个子元素.

我使用的是单页组件,这是我的设置:

// parent
export default {
  mounted: function () {
    this.$on('myEvent', function (msg) {
    console.log('caught in parent', msg)
  });
 },
 components: {
  'child': child,
 },
}

// child
this.$emit('myEvent', true)

我如何在父vm上接收此事件?注意,我不想在html中使用$on.我希望事件接收逻辑在虚拟机中的应该位置.

谢谢

推荐答案

关于$emitVues个文档不是很全面,但是,有几种方法可以做到这一点.首先,如果要使用this.$on(),必须在要发送消息的vue模型上使用$emit,因此,如果从组件发送,则可以使用以下方式向直接父级发送:

this.$parent.$emit('myEvent',true);

但是,如果您有一个长的父链,这可能会成为问题,因为您必须在子链上增加$emit个,因此在这种情况下,您可以使用Vue实例作为总线:

// In the root as a global variable so all components have access
var bus = new Vue({});

或者,如果您使用的是单文件组件.

window.bus = new Vue({});

然后在接收器中:

bus.$on('myEvent',() => {
   // Do stuff
});

在emits 器中:

bus.$emit('myEvent',true);

最后,如果你发现对于一辆简单的公交车来说,app变得太复杂了,那么你可以使用vuex:

https://vuex.vuejs.org/en/index.html

Vue.js相关问答推荐

如何 for each 动态创建的按钮/文本字段设置唯一变量?

通过元素加中的正则表达式输入电话号码格式

在 vue.js 中添加新类时样式不适用

props至少应该定义它们的类型

nuxt.js - 预加载 .woff 字体加载为@font-face

如何使用 vue.js 获取本地 html 文件?

VuetifyJS,outer-link 未显示为光标

vuejs vue-cli 如何使用 console.log 而不会出现任何错误

Vue Table 2 - 自定义过滤器

如何在 Vue.js 中添加动态组件/部分

在 Vuejs 中Watch观察 window.scrollY 的变化

PhpStorm 中Expected预期表达式

Vuex - 何时从 http 服务器加载/初始化存储数据

如何在两个属性上使用 Vue/Vuetify 自动完成过滤器?

重新加载页面正在 vue 组件中的插槽上闪烁内容

如何从 vue 组件调用 App.vue 中的方法

Vue JS 在渲染前等待数据

用于本地编辑的 Vuex 克隆对象

laravel vuejs/axios put request Formdata 为空

VS Code - 在 .vue 文件中启用 autoClosingTags 选项