vue3+ts 依赖注入 provide inject

父级:

<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>

儿子级别:

<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>

孙子级:

<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>

效果图:
vue3+ts 依赖注入 provide inject_第1张图片

你可能感兴趣的:(vue.js,javascript,前端)