由于某种原因,发出的事件无法由父组件处理
HTML:
<template id="parent-template">
<div>
<h1>Parent: {{message}}</h1>
<child-component message="Child message"></child-component>
</div>
</template>
<template id="child-template">
<div>
<h2>Child: {{message}}</h2>
<button v-on:click="changeMessage('Changed')">Change</button>
</div>
</template>
<div id="app">
<parent-component message="Parent message"></parent-component>
</div>
JS(es5):
孩子:
Vue.component("child-component", {
template: "#child-template",
props:['message'],
methods:{
changeMessage: function(newMessage){
this.message = newMessage;
this.$emit("message-changed", newMessage);
}
}
});
父母:
Vue.component("parent-component", {
template: "#parent-template",
props:['message'],
mounted: function(){
var v = this;
this.on("message-changed", function(newValue){
alert("Emit handled!");
v.message = newValue;
});
}
});
因此,一切看起来都很好,但是事件触发时什么也没发生。为什么?
答案 0 :(得分:0)
您无法在已安装的函数上检查发出的事件,因为此时尚未实例化子Vue实例。如果要在运行完所有代码后运行代码,这就是我假设要执行的操作,则需要在打勾后运行代码。
this.$nextTick(function () { // Your code goes here }
此外,为清楚起见,我通常会在HTML内部执行v-on:message-changed="parentMethod()"
。这样,父级不会与已安装的子级组件紧密耦合。
<child-component v-on:message-changed="parentMethod()"> </child-component>
以下是有关我提供的安装信息的Vue文档: https://vuejs.org/v2/api/#mounted