【问题标题】:Vue emit (did not listen the emitting event from the child)Vue 发射(没有监听来自孩子的发射事件)
【发布时间】:2020-09-26 06:21:22
【问题描述】:

我是初学者,我尝试了 vue emit 事件。但该事件不听父母的。请帮帮我!!

在 App.vue 中

<app-header v-bind:somethings='name' @custom-event-name="setName"></app-header> 

setName(childName){
 this.name= childName;

}

在 Body.vue 中

<button @click="changeName"> click me to change name </button>

changeName: function(){
        this.$emit('custom-event-name', 'Some Value');    }

【问题讨论】:

  • app-header组件是如何导入的?
  • 您是否也在导入和使用Body 组件?
  • 我将app-header导入为以下兄弟@&lt;script&gt; import Header from './components/Header.vue'; export default { components:{ 'app-header': Header, }, data () { return { name: 'John', } }, methods: { setName(childName){ this.name= childName; } }&lt;/script&gt;

标签: vue.js events emit


【解决方案1】:

根据我在您的 script 部分中看到的情况,您没有导入 Body 组件,这是您尝试发出事件的地方。

现在你有这个:

<script>
import Header from './components/Header.vue';
export default {
  components:{
    'app-header': Header,
    'app-body' : Body
  },
  data () { 
    return  {
      name: 'John', 
    } 
  }, 
  methods: {
    setName(payload) {
      this.name = payload;
    }
  }
}
</script>

Body 组件没有 import 语句,因此您的父组件不知道 Body 是什么。要解决这个问题,您只需要像为Header 所做的那样添加一个导入。它可能看起来像这样:import Body from './components/Body.vue';

现在Body 组件正在被使用,您需要将它包含在您的template 中。您将执行与 app-header 相同的操作,并包含类似 &lt;app-body&gt;&lt;/app-body&gt; 的标签。最后,您需要添加事件侦听器,以便父级知道何时运行setName。这被添加到app-body 标签中,最终看起来像这样:&lt;app-body @custom-event-name="setName"&gt;&lt;/app-body&gt;

【讨论】:

    猜你喜欢
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2017-03-07
    相关资源
    最近更新 更多