【问题标题】:Vue - Passing data from child to parent - Basic emit not workingVue - 将数据从孩子传递给父母 - 基本发射不起作用
【发布时间】:2018-05-18 15:17:57
【问题描述】:

我有一个基本的 Vue2 组件,我正在尝试使用 $emit 将数据从子组件传递到父组件。 注意, my-component 包含一个表格,当我单击一行时,onRowClick 会成功触发,并将“foobar”输出到控制台。出于某种原因,我无法让父方法在 $emit 上触发,并且没有将成功记录到控制台。知道这是为什么吗?

import Vue from 'vue';
import MyComponent from "./components/MyComponent.vue";

window.onload = function () {
   var main = new Vue({
      el: '#app-v2',
      components: { MyComponent },
      methods: {
         onCouponApplied(data) {
            console.log("Success, coupon applied, " + data);
            this.saying = "Sunglasses are " + data; //Sunglasses are cool
         }
      },
      data: {
         contactEditPage: {
            saying: ""
         }
      }
   });
}

MyComponent.vue

export default {
        methods: {
            onRowClick(event){ 
               this.$emit('applied', 'Cool');
               console.log("foobar");
            }

HTML

<div id="app-v2">
    <my-component @applied="onCouponApplied"></my-component>
     {{ saying }} //trying to output: sunglasses are cool
</div>

【问题讨论】:

  • 可能$emit 找不到父组件。尝试从您的代码中删除 window.onload 包装器...
  • @AnchovyLegend,这是一个 Plunker (plnkr.co/edit/yldNSHD5S55VykT2FrRn?p=preview),其中包含足够多的代码片段。问题必须在您发布的内容之外,因为该示例似乎有效。

标签: javascript ecmascript-6 vue.js vuejs2 vue-component


【解决方案1】:

我遇到了同样的问题。我通过使用 $root 解决了这个问题。

例如在父级Vue组件中

mounted(){
    this.$root.$on('event-name',function(value){
        // code
    });
},

子组件应该是这样的:

this.$root.$emit('event-name',[data]);

希望能帮到你。

【讨论】:

  • 谢谢你,比这里的许多决定更好、更容易一百倍
  • 您可以使用 VueX 作为替代解决方案。我认为使用这种方法也很好。
猜你喜欢
  • 2019-11-09
  • 2018-05-03
  • 2019-04-17
  • 2021-10-16
  • 1970-01-01
  • 2021-10-31
  • 1970-01-01
  • 2023-02-08
  • 2022-08-03
相关资源
最近更新 更多