vue3+ts 依赖注入 provide inject

父级:

handlebars 复制代码
<template>
  <div>
    <h1>App.vue (爷爷级别)</h1>
    <label>
      <input type="radio" v-model="colorVal" value="red" name="color" />
      红色
    </label>
    <label>
      <input type="radio" v-model="colorVal" value="pink" name="color" />
      粉色
    </label>
    <label>
      <input type="radio" v-model="colorVal" value="yellow" name="color" />
      黄色
    </label>
    <div class="box"></div>
    <hr />
    <provideAVue></provideAVue>
  </div>
</template>

<script setup lang="ts">
import { ref, provide } from "vue";
import provideAVue from "./components/provideA.vue";
const colorVal = ref<string>("red");
provide("color", colorVal);
</script>

<style>
.box {
  height: 50px;
  width: 50px;
  border: 1px solid #ccc;
  background: v-bind(colorVal);
}
</style>

儿子级别:

handlebars 复制代码
<template lang="html">
  <div>
    <h1>provideA.vue(儿子级别)</h1>
    <div class="box"></div>
    <hr />
    <provideBVue></provideBVue>
  </div>
</template>
<script lang="ts" setup>
import { inject } from "vue";
import type { Ref } from "vue";
import provideBVue from "./provideB.vue";
const color = inject<Ref<string>>("color");
</script>
<style lang="scss">
.box {
  width: 50px;
  height: 50px;
  border: 1px solid #ccc;
  background: v-bind(color);
}
</style>

孙子级:

handlebars 复制代码
<template lang="html">
  <div>
    <h1>provideA.vue(孙子级别)</h1>
    <div>
      <button @click="change">修改 provide的值 yellow</button>
    </div>
    <div class="box"></div>
    <hr />
  </div>
</template>
<script lang="ts" setup>
import { inject } from "vue";
import type { Ref } from "vue";
const color = inject<Ref<string>>("color");
const change = () => {
  color!.value = "yellow";
};
</script>
<style lang="scss">
.box {
  width: 50px;
  height: 50px;
  border: 1px solid #ccc;
  background: v-bind(color);
}
</style>

效果图:

相关推荐
子兮曰13 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖13 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神13 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛15 小时前
Nginx日志切分
服务器·前端·nginx
Daniel李华15 小时前
echarts使用案例
android·javascript·echarts
北原_春希15 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS15 小时前
echarts天气折线图
javascript·vue.js·echarts
尽意啊15 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜15 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive15 小时前
Vue3使用ECharts
前端·javascript·echarts