组件通信方式之ref与$parent
直接上代码ba~
父组件
<template>
<div class="father">
<h1>我是父组件,小金库有:{{ money }}</h1>
<button @click="handler">找儿子借10块</button>
<div class="children">
<Son ref="son"></Son>
<Dau></Dau>
</div>
</div>
</template>
<script setup lang="ts">
//ref:可以获取真实的DOM节点,可以获取到子组件实例VC
//$parent:可以在子组件内部获取到父组件的实例
import { ref } from "vue";
import Son from "./SonM.vue";
import Dau from "./DauM.vue";
let money = ref(10000000000);
//获取子组件的实例!!
let son = ref();
const handler = () => {
money.value += 10;
console.log(son.value);
son.value.money -= 10;
};
//对外暴露
defineExpose({ money });
<style scoped>
.father {
width: 100vw;
height: 400px;
background: pink;
}
.children {
display: flex;
}
</style>
</script>
儿子组件
<template>
<div class="son">
<h3>我是儿子,小金库有:{{ money }}</h3>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
let money = ref(666);
//组件内部数据对外关闭的,别人不能访问
//如果想让外部访问需要通过defineExpose方法对外暴露
defineExpose({ money });
</script>
<style scoped>
.son {
width: 300px;
height: 300px;
background: skyblue;
}
</style>
女儿组件
<template>
<div class="dau">
<h3>我是女儿,小金库有:{{ money }}</h3>
<button @click="handler($parent)">找爸爸借100</button>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
let money = ref(10000);
const handler = ($parent) => {
money.value += 100;
// console.log($parent.money);
console.log($parent);
$parent.money -= 100;
};
</script>
<style scoped>
.dau {
width: 300px;
height: 300px;
background: hotpink;
}
</style>
总结
1.
ref
:可以获取真实的DOM节点,可以获取到子组件实例
$parent
:可以在子组件内部获取到父组件的实例
2.如果想让外部访问需要通过defineExpose
方法对外暴露
如有错误,欢迎指出,我修正!谢谢!