定义
- 可以从最上层组件,传递参数给其所有子组件,并且子组件也可以修改值
- 修改的值在该组件内(包括子组件)全局生效
例子
爷爷组件
<template>
<div>
<div>爷爷组件:<t-input v-model="yeyeValue" /></div>
<br />
<b-vue />
</div>
</template>
<script lang="ts">
export default {
name: 'ApplyAWSIndex',
};
</script>
<script setup lang="ts">
import { ref, provide, readonly } from 'vue';
import BVue from './B.vue';
const yeyeRefValue = ref('');
provide('yeyeValue', yeyeRefValue);
</script>
<style scoped lang="less">
// 注意这里,vue3的css也支持用v-bind的方式绑定变量,可以通过这个动态修改某些css参数
.box {
background-color: v-bind(yeyeValue);
}
</style>
儿子组件
<template>
<div style="border: 1px solid black; height: 800px; background-color: #1dc8e5">
我是B
<label for="name1">儿子组件获取爷爷组件传递的值:{{ yeyeValue }}</label>
<br />
<c-vue />
</div>
</template>
<script setup lang="ts">
import { inject, Ref } from 'vue';
import CVue from './C.vue';
const yeyeValue = inject<Ref<string>>('yeyeValue');
</script>
<style scoped></style>
孙子组件
<template>
<div style="border: 1px solid black; height: 500px; background-color: #3d87ff">
我是C
<label for="name1">孙子组件获取爷爷组件传递的值:{{ yeyeValue }}</label>
<div>
<t-button @click="onClick">点我修改爷爷传过来的值,影响全局</t-button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, inject } from 'vue';
import type { Ref } from 'vue';
const yeyeValue = inject<Ref<string>>('yeyeValue', ref('defaultValue默认值'));
const onClick = () => {
yeyeValue.value = '被孙子改了值';
};
</script>
<style scoped>
.
</style>

