【问题标题】:Can't pass data from children to parent component with emit无法使用发射将数据从子组件传递到父组件
【发布时间】:2017-07-28 22:56:36
【问题描述】:

我需要将数据从子组件传递给父组件。代码很简单,但我不明白我缺少什么以及缺少什么。

export default {
  name: 'TableOfContent',
  props: ['itemGUID'], // is it nessosary? 
  methods: {
      itemClick(itemGUID)
      {
        console.log(itemGUID);
        this.$emit('newchapter', itemGUID) // passing GUID to parent
      }
  }
}

父模板:

<template>
    <div class="Book" v-on:newchapter="foo(itemGUID)">
        {{msg}}
    </div>
</template>


<script>
import toc from './TableOfContent.vue'

export default {
  name: 'mybook',
  data () {
    return {
      msg: 'my main book'
    }
  },
  methods:
  {
      foo(itemGUID)
      {
          console.log("GUID is: ", itemGUID);
      }
  },

   components: {toc}

}
</script>

此代码不起作用:(

【问题讨论】:

  • 你是不确定的吗?
  • 你在模板哪里使用TableOfContent ,你能创建一个小提琴吗? Here 是在发出事件中发送参数的一个示例。
  • @Saurabh 看起来foo() 没有电话。我没有得到任何安慰。我会努力做到的。
  • tableofcontent 组件中应该是this.$emit('newchapter', this.itemGUID)
  • @Belmin 和 .this 我在 itemClick 方法中变得未定义。

标签: vue.js


【解决方案1】:

只需在模板中执行以下操作:

<template>
    <div class="Book" v-on:newchapter="foo">
        {{msg}}
    </div>
</template>

【讨论】:

  • 同样的效果 :( 对不起,我没有 jsfiddle,这对我来说有点难。子组件的 console.log 工作正常。我在控制台上看到值。但是在父组件中 foo似乎没有触发,因为我在控制台上看不到(数据没有通过?)
  • @user1432751 你在哪里使用模板中的TableOfContent,
  • 无处可去。我应该使用它吗?如果我这样做:```
    {{msg}}
    ``` 我得到了 Table 的完整副本的内容。但我只需要从 TOC 组件传递 ID
  • @user1432751 只有你才能使用该组件,对吧?
  • 什么意思?我只需要将 ID 传递给其他组件。当用户点击 TOC 元素时,我的应用会切换内容。
猜你喜欢
  • 2021-02-22
  • 2019-02-27
  • 2017-04-20
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多