爷级,css中使用 background-color: v-bind(color);可绑定setup中的值
<template>
<h1>APP.vue</h1>
<hr>
<label >
<input type="radio" value="red" name="color" v-model="color">
我是红色
</label>
<label >
<input type="radio" value="yellow" name="color" v-model="color">
我是黄色
</label>
<label >
<input type="radio" value="green" name="color" v-model="color">
我是绿色
</label>
<div class='box'></div>
<Avue></Avue>
</template>
<script setup lang="ts">
import {reactive,ref,provide} from 'vue'
import Avue from "./components/A.vue";
const color =ref<string>('red')
provide('color',color)
</script>
<style>
.box{
width: 50px;
height: 50px;
border: 1px solid red;
background-color: v-bind(color);
}
</style>
a页面,父级
<template>
<h1>A.vue</h1>
<hr />
<div class="box"></div>
<Bvue></Bvue>
</template>
<script lang="ts" setup>
import Bvue from '../components/B.vue'
import type {Ref} from 'vue'
import { inject } from 'vue';
const colorActive =inject<Ref<string>>('color')
</script>
<style>
.box {
width: 50px;
height: 50px;
border: 1px solid red;
background-color: v-bind(colorActive);
}
</style>
b页面,孙级
<template>
<h1>B.vue</h1>
<hr />
<div class="box"></div>
</template>
<script lang="ts" setup>
import { inject } from 'vue';
import type {Ref} from 'vue'
const colorActive =inject<Ref<string>>('color')
</script>
<style>
.box {
width: 50px;
height: 50px;
border: 1px solid red;
background-color: v-bind(colorActive);
}
</style>
若想在b中修改颜色
<template>
<h1>B.vue</h1>
<hr />
<button @click="change">修改颜色</button>
<div class="box"></div>
</template>
<script lang="ts" setup>
import { inject } from 'vue';
import type {Ref} from 'vue'
const colorActive =inject<Ref<string>>('color')
const change=()=>{
//colorActive?.value='yellow'//这样写报错,因为返回值可能是undefind,可使用非空断言
colorActive!.value='yellow'
}
</script>
<style>
.box {
width: 50px;
height: 50px;
border: 1px solid red;
background-color: v-bind(colorActive);
}
</style>
若不想被子组件改变则爷级需要包一个readonly
app页面
<script setup lang="ts">
import {reactive,ref,provide,readonly} from 'vue'
import Avue from "./components/A.vue";
const color =ref<string>('red')
provide('color',readonly(color))
</script>