<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app">
<p>Messages: {{ messages | json }}</p>
<child-component></child-component>
</div>
<template id="child-component">
<input v-model="msg" />
<button v-on:click="notify">Dispatch Event</button>
</template>
<script src="js/vue.js"></script>
<script>
// 注册子组件
Vue.component('child-component', {
template: '#child-component',
data: function() {
return {
msg: ''
}
},
methods: {
notify: function() {
if (this.msg.trim()) {
this.$dispatch('child-msg', this.msg)
this.msg = ''
}
}
}
})
// 初始化父组件
new Vue({
el: '#app',
data: {
messages: []
},
events: {
'child-msg': function(msg) {
this.messages.push(msg)
}
}
})
</script>
</body>
</html>
![]()
![]()
![]()
- 子组件的button元素绑定了click事件,该事件指向notify方法
- 子组件的notify方法在处理时,调用了$dispatch,将事件派发到父组件的child-msg事件,并给该该事件提供了一个msg参数
- 父组件的events选项中定义了child-msg事件,父组件接收到子组件的派发后,调用child-msg事件。