组件通信方式之provide与inject
直接上代码ba~
祖先组件
<template>
<div class="grandFather">
<h3>祖先组件car:{{ car }}</h3>
<Child></Child>
</div>
</template>
<script setup lang="ts">
//vue3提供provide(提供)与inject(注入),可以实现隔辈组件传递数据
import Child from "./FatherM.vue";
import { ref, provide } from "vue";
//祖先组件给后代组件提供数据
//两个参数:第一个参数就是提供的数据key
//第二个参数:祖先组件提供数据
let car = ref("法拉利");
provide("token", car);
</script>
<style scoped>
.grandFather {
width: 500px;
height: 500px;
background: violet;
}
</style>
父亲组件
<template>
<div class="container">
<h3>父亲组件</h3>
<Child></Child>
</div>
</template>
<script setup lang="ts">
import Child from "./SonM.vue";
</script>
<style scoped>
.container {
width: 400px;
height: 400px;
background: pink;
}
</style>
儿子组件
<template>
<div class="son">
<h3>孙子组件car:{{ car }}</h3>
<button @click="handler">我想换一辆自行车</button>
<div>{{ carss }}</div>
</div>
</template>
<script setup lang="ts">
import { inject } from "vue";
//注入祖先组件提供数据
//需要参数:即为祖先提供数据的key
let car = inject("token");
// 注入一个值,若为空则使用提供的默认值
const carss = inject("tok", "啦啦啦");
const handler = () => {
car.value = "自行车";
console.log(car);
};
</script>
<style scoped>
.son {
width: 200px;
height: 200px;
background: skyblue;
}
</style>
总结
1.vue3提供
provide(提供)
与inject(注入)
,可以实现隔辈组件传递数据
2.provide有两个参数:provide("TOKEN", car);
第一个参数是提供的数据key
第二个参数为提供的数据
3.注入一个值时,支持使用默认值,若为空则使用提供的默认值
const bar = inject(‘foo’, ‘default value’)