Vuejs 2:将事件从组件发送到父组件

时间:2017-02-10 09:39:50

标签: vuejs2

我有这段代码:

HTML

<div id="app">
  {{text}}
  <my-component></my-component>
</div>

JS

Vue.component('my-component', {
  template: '<button @click="click">Click me</button>',
  methods: {
    click() {
        this.$emit('send', 'bye')
    }
  }
})

new Vue({
  el: "#app",
  data: {
    text: "hello"
  },
  created() {
    this.$on('send', (text) => {
        this.text = text;
    })
  }
})

工作示例:https://jsfiddle.net/rjurado/y4yf6nve/

为什么事件send不起作用?

3 个答案:

答案 0 :(得分:31)

父组件可以使用v-on直接侦听从子组件发出的事件。

<强> HTML

<div id="app">
  {{text}}
  <my-component v-on:send="sendText"></my-component>
</div>

<强> JS

Vue.component('my-component', {
  template: '<button @click="click">Click me</button>',
  methods: {
    click() {
      this.$emit('send', 'bye')
    }
  }
})

new Vue({
  el: "#app",
  data: {
    text: "hello"
  },
  methods: {
    sendText(text) {
      alert(text)
    }
  }
})

工作示例:https://jsfiddle.net/y4yf6nve/2/

答案 1 :(得分:27)

this.$emit仅指Vue组件。您需要使用root instance属性与根实例中的组件进行通信。所以基本上为事件添加root:

this.$root.$emit('send', 'bye')

this.$root.$on('send', (text) => {
      this.text = text;
  })

工作示例:jsFiddle

Vue.js中央事件总线

更好的方法是使用中央事件总线:docs

var bus = new Vue();

Vue.component('my-component', {
  template: '<button @click="click">Click me</button>',
  methods: {
    click() {
        bus.$emit('send', 'bye')
    }
  }
})

new Vue({
  el: "#app",
  data: {
    text: "hello"
  },
  created() {
    bus.$on('send', (text) => {
        this.text = text;
    })
  }
})

工作示例:jsFiddle

答案 2 :(得分:4)

对于将来的引用,自定义事件名称不能是camelCased。 使用this.$emit('send_event', 'bye')代替this.$emit('sendEvent', 'bye') https://github.com/vuejs/vue/issues/4044

相关问题