vue3 provide/inject

爷级,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>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容