我正在使用 Vue.js 2.0,我正在尝试从“子组件”发出一个事件

I am using Vue.js 2.0 and I am trying to emit an event from `child component`

我正在使用 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 的新手。

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

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

你必须监听事件,如果你查看 Emit Documentation,它期望作为第一个参数的事件名称作为字符串,然后是你想要传递给的值(如果有)听众.

所以它将是:

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

方法将是:

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

在 child 上:

this.$emit('nameOfEvent', someValue)

你的情况

您没有传递值,所以 this.$emit('confirmed')<ConfirmMessage :confirmed="confirmed"> 就足够了