核心:通过自定义事件的形式将父组件中的方法传递给子组件 子组件放入父模板中时 给子组件绑定一个自定义事件 @xx=”Xjk” 子组件的事件里执行
this.$emit(‘自定义事件名称’,需要传递的参数) 表示执行父组件的自定义事件
实例方法 $emit
- 参数:
{string} eventName[...args]
触发当前实例上的事件。附加参数都会传递给监听器回调
- 案例:让子组件中的数据HongBao传输给父组件中的数据XJK(儿子给父亲红包父亲炫耀金库)
父组件:
<template id="father"><P>Father:I have {{Xjk}}</P><!-- 使用自定义事件【事件名自定义】形式将父组件中的方法传递给子组件 --><Son @money="add"></Son></template>
app.component('Father', {template: '#father',data() {return {Xjk: 500}},methods: {add(money) {this.Xjk += money}}})
子组件:
<template id="son"><button @click="give">give you money</button></template>
app.component('Son', {template: '#son',data() {return {HongBao: 8888,}},methods: {give() {//执行父组件的自定义事件 this.$emit(自定义事件名,参数)this.$emit('money', this.HongBao)}}})
