【问题标题】:Emited event does't handled by parent component in Vue 2发出的事件不由 Vue 2 中的父组件处理
【发布时间】:2020-01-17 09:54:09
【问题描述】:

由于某种原因,发出的事件不被父组件处理

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;
    });
  }
});

所以,一切看起来都很好,但是当事件触发时没有任何反应。为什么?

【问题讨论】:

    标签: vuejs2 vue-events


    【解决方案1】:

    您无法检查已挂载函数上发出的事件,因为此时未实例化子 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

    【讨论】:

      猜你喜欢
      • 2021-05-05
      • 2021-12-14
      • 2018-09-27
      • 2019-08-11
      • 2021-07-26
      • 2019-11-13
      • 2018-04-18
      • 2017-07-09
      • 2017-07-07
      相关资源
      最近更新 更多