首页 > 解决方案 > vue 中的全局 $root 事件永远不会到来

问题描述

我有一个动态实例化的 vue 组件,它应该通过一个事件与根 vue 实例进行通信。组件(一个对话框表单)发出事件,this.$root.$emit()根监听,this.$root.$on()没有事件到达。当我调试时,我看到两个不同的实例this.$root不相同:

2 个不同的 $roots - wtf?

我究竟做错了什么?

https://codepen.io/anon/pen/XGoPmj

// Define component
const StepForm = Vue.extend({
    methods: {
        save() {
            console.log("sending event to ", this.$root)
            this.$root.$emit('stepSave');
        }
    }
});
// Dynamically create component
let frm = document.createElement('div');
frm.setAttribute('id', 'myForm');
document.getElementById('root').appendChild(frm);
let dialog = new StepForm().$mount('#myForm');;

new Vue({
  el: '#root',
  mounted() {
    this.$root.$on('stepSave', ()=>{
      // This never arrives!
      console.log("Got the event!")
    });
    console.log('I am the root', this.$root)
  }
});

function doIt() {
  dialog.save()
}

更新:解决方案:TLDR:基本上,您必须在根 vue 实例之后创建组件并将该实例传递给您的构造函数

标签: vue.js

解决方案


您需要在创建组件时指定父级。否则,$root将等于组件本身:

dialog = new StepForm({
  parent: root
}).$mount('#myForm');

[ https://jsfiddle.net/stdob__/qcusdr67/ ]


推荐阅读