Provide / Inject
使用场景
组件深度嵌套,结构比较复杂的时候,用props一级一级传太麻烦了,中间还容易出错,这时可以在顶层父组件使用Provide,后代组件中使用Inject传值。
父组件
<template>
<div class="App">
<button>我是App</button>
<A></A>
</div>
</template>
<script setup lang='ts'>
import { provide, ref } from 'vue'
import A from './components/A.vue'
let flag = ref<number>(1)
provide('flag', flag)
</script>
<style>
.App {
background: blue;
color: #fff;
}
</style>
子组件
<template>
<div style="background-color: green;">
我是B
<button @click="change">change falg</button>
<div>{{ flag }}</div>
</div>
</template>
<script setup lang='ts'>
import { inject, Ref, ref } from 'vue'
const flag = inject<Ref<number>>('flag', ref(1))
const change = () => {
flag.value = 2
}
</script>
<style>
</style>
如果传递普通的值,是不具有响应式的,需要通过ref、reactive添加响应式
标注类型
上面的类型推断是在inject的时候断言,使用上体验并不好,因此参考官网 为 provide / inject 标注类型
import { provide, inject } from 'vue'
import type { InjectionKey } from 'vue'
const key = Symbol() as InjectionKey<string>
const key1: InjectionKey<string> = Symbol('')
provide(key, 'foo') // 若提供的是非字符串值会导致错误
const foo = inject(key) // foo 的类型:string | undefined
建议将注入 key 的类型放在一个单独的文件中,这样它就可以被多个组件导入。
当使用字符串注入 key 时,注入值的类型是 unknown,需要通过泛型参数显式声明:
const foo = inject<string>('foo') // 类型:string | undefined
注意注入的值仍然可以是 undefined,因为无法保证提供者一定会在运行时 provide 这个值。
当提供了一个默认值后,这个 undefined 类型就可以被移除:
const foo = inject<string>('foo', 'bar') // 类型:string
如果你确定该值将始终被提供,则还可以强制转换该值:
const foo = inject('foo') as string
