1.子给父通信
- this.$emit()
- this.$parent//获取父组件,然后直接调用父组件的方法
2.父给子通信
给子组件添加一个ref属性
this.$refs//获取所有ref属性
子组件
<template>
<div>
<div>儿子健康:{{health}}</div>
<button @click="emit1">打父组件</button>
<button @click="emit2">打父组件</button>
</div>
</template>
<script>
export default {
data(){
return{
health:100
}
},
methods: {
toHeart(){
this.health--
},
//方式1
emit1(){
this.$emit('da')
},
emit2(){
this.$parent.toHeart()
}
},
}
</script>
父组件
<template>
<div>
<div>爸爸:{{health}}</div>
<button ref="childs" @click="hit">打儿子</button>
<child ref="child" @da="toHeart" />
</div>
</template>
<script>
import child from "./child.vue"
export default {
components:{
child
},
data(){
return{
health:100
}
},
methods: {
toHeart(){
this.health--
},
hit(){
this.$refs['child'].toHeart()
//父掉子
// this.$refs['child'].toHeart();
},
},
}
</script>