【问题标题】:I am using Vue.js 2.0 and I am trying to emit an event from `child component`我正在使用 Vue.js 2.0,我正在尝试从“子组件”发出事件
【发布时间】:2018-08-29 11:35:35
【问题描述】:

我正在使用 Vue.js 2.0,我试图从 child componentparent component 发出一个事件,但它不起作用。

你可以在下面看到我的代码:

子组件:

<template>
  <button @click="confirmSendMessage">Send</button>
</template>

<script>
  export default {
    methods: {
      confirmSendMessage () {
        this.$emit('confirmed')
      }
    }
</script>

父组件:

<template>
    <ConfirmMessage/>
</template>

<script>
    import ConfirmMessage from './ConfirmMessage'
    export default {
        events: {
           confirmed() {
              console.log('confirmed')
           }
        },
        components: {
            ConfirmMessage
        }
   }
</script>

当我单击该按钮时,Chrome 控制台上没有显示任何内容。 我不知道为什么。有谁能够帮我?我是 Vue JS 的新手。

【问题讨论】:

    标签: javascript vue.js emit


    【解决方案1】:

    您错过了监听发出的事件。使用v-on监听事件:

    <!--                               vv -> call method -->
    <ConfirmMessage v-on:confirmed="confirmed" />
    <!--                  ^^ -> emitted event -->
    

    【讨论】:

    • 现在我在控制台上得到了这个:Property or method "confirmed" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.:S
    【解决方案2】:

    您必须侦听事件,如果您查看Emit Documentation,它需要将事件名称作为字符串的第一个参数,然后是您想要传递给侦听器的值(如果有)。

    原来如此:

    <confirm-message :nameOfEvent="functionToExecuteWhenTheEventIsEmitted" />
    

    方法是:

    functionToExecuteWhenTeEventIsEmitted(someValue) { //do whatever with someValue}
    

    关于孩子:

    this.$emit('nameOfEvent', someValue)
    

    你的情况

    你没有传递值,所以 this.$emit('confirmed')&lt;ConfirmMessage :confirmed="confirmed"&gt; 就足够了

    【讨论】:

    • 不需要传递值。
    • 这是一个完整的例子,你可以避免它,然后使用事件的名称
    • 从 Vue 2 开始,您应该使用 kebab-case 作为事件名称,否则它将不起作用,如 docs 中所述
    猜你喜欢
    • 2021-06-24
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 2018-05-11
    • 2018-05-19
    相关资源
    最近更新 更多