该节教程代码可经过npm start运行devServer,在http://localhost:8080/查看效果git
代码示例:/lesson17/src/components/parent.js,/lesson17/src/components/child.jsgithub
经过调用组件实例的$emit(事件名, 参数),向组件发送一个事件。 在组件的生命周期created中,使用\this.$on(事件名, 回调函数),在回调函数中能够接收到参数,以此实现组件间通讯。npm
父组件代码:bash
export default Vue.component('parent', {
data() {
return {
num: 0,
};
},
components: {
Child
},
created() {
this.$on('add', function (n) {
this.num = this.num + n
})
},
methods: {
addChild() {
this.$refs.child.$emit('add', 5)
},
},
template: `
<div>
<div>父级
num:{{num}}
<br/><input type="button" value="子级num1 + 5" @click="addChild" />
<child ref="child" :parent="this"></child>
</div>
`
});
复制代码
子组件代码:less
export default Vue.component('parent', {
props: ['parent'],
data() {
return {
num: 0,
};
},
methods: {
addParent() {
this.parent.$emit('add', 5)
},
},
created() {
this.$on('add', function (n) {
this.num = this.num + n
})
},
template: `
<div>
子级
num:{{num}}
<br/><input type="button" value="父级num1 + 5" @click="addParent" />
</div>
`
});
复制代码