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

dri*_*nor 21 vuejs2

我有这个代码:

HTML

<div id="app">
  {{text}}
  <my-component></my-component>
</div>
Run Code Online (Sandbox Code Playgroud)

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;
    })
  }
})
Run Code Online (Sandbox Code Playgroud)

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

为什么事件send不起作用?

sme*_*mek 33

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

HTML

<div id="app">
  {{text}}
  <my-component v-on:send="sendText"></my-component>
</div>
Run Code Online (Sandbox Code Playgroud)

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)
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

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


t_d*_*m93 32

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

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

this.$root.$on('send', (text) => {
      this.text = text;
  })
Run Code Online (Sandbox Code Playgroud)

工作示例: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;
    })
  }
})
Run Code Online (Sandbox Code Playgroud)

工作示例:jsFiddle


kun*_*dan 5

为了将来参考,自定义事件名称不能是驼峰式的。使用this.$emit('send_event', 'bye')而不是this.$emit('sendEvent', 'bye') https://github.com/vuejs/vue/issues/4044