爺級(jí),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頁(yè)面,父級(jí)
<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頁(yè)面,孫級(jí)
<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'//這樣寫報(bào)錯(cuò),因?yàn)榉祷刂悼赡苁莡ndefind,可使用非空斷言
colorActive!.value='yellow'
}
</script>
<style>
.box {
width: 50px;
height: 50px;
border: 1px solid red;
background-color: v-bind(colorActive);
}
</style>
若不想被子組件改變則爺級(jí)需要包一個(gè)readonly
app頁(yè)面
<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>