vue3+ts 依赖注入provide inject的用法
作者:你的美,让我痴迷
vue3中引入新的组件传值方式,就是provide/inject依赖注入模式,本文主要介绍了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的用法的文章就介绍到这了,更多相关vue3 ts 依赖注入内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!