1.父组件
<template>
<div class="parent">
<son ref="son" :sonNumber="parentNumber" :parentMethod="parentMethod" @sendSonNumber="receiveSonNumber" @sonCallParentFun="parentFun"></son>
<button @click="handleSonNumber">点击更改子组件的值</button>
<button @click="callSonFun">点击调用子组件的方法</button>
</div>
</template>
<script>
import son from "./son.vue";
export default {
name: "parent",
components: {
son,
},
data() {
return {
parentNumber: 1,
};
},
methods: {
handleSonNumber() {
this.parentNumber++
},
receiveSonNumber(num) {
this.parentNumber = num
},
callSonFun() {
this.$refs.son.sonFun()
},
parentFun() {
this.parentNumber = 99
},
parentMethod() {
this.parentNumber = 200
},
},
};
</script>
<style scoped>
.parent {
background: #ffbece;
}
</style>
2. 子组件
<template>
<div class="son">
<span style="color:#ff0000;">{{ sonNumber }}</span>
<button @click="clickSon">点击按钮向父组件传值</button>
<button @click="callParentFun">点击调用父组件的方法1</button>
<button @click="childMethod">点击调用父组件的方法2</button>
</div>
</template>
<script>
export default {
name: "son",
props: {
sonNumber: {
type: Number,
default: 0,
},
parentMethod: {
type: Function,
default: null,
},
},
data() {
return {};
},
methods: {
clickSon() {
this.$emit('sendSonNumber',50)
},
sonFun() {
this.$emit('sendSonNumber',11)
},
callParentFun() {
this.$emit('sonCallParentFun')
},
childMethod() {
this.parentMethod()
},
},
};
</script>
<style scoped>
.son {
background: #bef2ff;
}
</style>