VueJS如何用emit替换dispatch

时间:2017-03-26 09:21:05

标签: javascript vue.js vuejs2

我想从子组件向父组件发送信号。我不想使用Vuex作为我的VueJS知识水平Vuex太复杂了。我正在使用单个文件组件。

child.vue

<script>
export default {
name: 'ChildComponent',
methods: {
    // ajax post here ...
    if (response.data.status === 'accepted'){
      this.$emit('send-data', 'accepted')
    }

}

parent.vue

<script>
import ChildComponent from './ChildComponent.vue'
export default {
    name: 'Parent',
    data () {
      return {
        stage: 1
      }
    },
  components: {
      ChildComponent
  },
  // how can I replace 'events' with $on in a single file component and listen for events after all components have been created
  events: {
  'send-data': function (dataResponse) {
    if (dataResponse === 'accepted'){
      this.stage = 2
    }
  }
}

VueJS文档中的示例为父级显示了类似的内容:

var eventHub = new Vue()
created: function () {
  eventHub.$on('add-todo', this.addTodo)
  eventHub.$on('delete-todo', this.deleteTodo)
},

但我想随时听取事件,而不仅仅是创作。如何更换父母的活动&#39;使用$ on函数?

1 个答案:

答案 0 :(得分:1)

如果您开始在created上侦听可能适用于组件整个生命周期的事件。或者,您可以在使用组件时使用v-on@快捷方式将事件设置为触发。

实施例

Vue.component('my-component', {
  template: '<div><button v-on:click="sendHello">hello</button></div>',
	
	methods:{
		sendHello: function(){
			console.log('hello');
          this.$emit('hello','hello')
		}
	}
});
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
	methods:{
		sayHi: function(){
			console.log('say hi')
		}
	}
})
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>VueJs</title>

</head>
<body>
<div id="app">
  <p>{{ message }}</p>
	<my-component v-on:hello='sayHi'></my-component>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>	
</body>
</html>