vue3 provide/inject

爺級(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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容