vue.js - vue 中的全局 $root 事件永远不会到来
问题描述
我有一个动态实例化的 vue 组件,它应该通过一个事件与根 vue 实例进行通信。组件(一个对话框表单)发出事件,this.$root.$emit()
根监听,this.$root.$on()
没有事件到达。当我调试时,我看到两个不同的实例this.$root
不相同:
我究竟做错了什么?
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 实例之后创建组件并将该实例传递给您的构造函数。
解决方案
您需要在创建组件时指定父级。否则,$root
将等于组件本身:
dialog = new StepForm({
parent: root
}).$mount('#myForm');
推荐阅读
- javascript - 将元素附加到表单中时是否有任何事件?
- c# - Application.OpenURL 在移动设备中不起作用
- javascript - 如何检查浏览器是否支持
- highcharts - HighCharts 我们无法在 y 轴上添加堆叠条作为时间
- json - 无法在 json Laravel 中返回关系元素
- sql - 通过匹配列的值从两个数据库中提取数据
- r - Rvest 网页抓取如何获取下一页
- python - 使用 python 2.7 构建 Conda noarch 包
- arrays - 如何在反应中使用 jest 编写单元测试用例?
- python - 如何在 python 2.7 中处理 Unicode 问题而不忽略