Provide / Inject

需要从父组件向子组件传递数据时会使用props。但有一些深度嵌套的组件,而深层的子组件只需要父组件的部分内容,这种情况下如果仍将prop沿着组件逐层传递,可能会很麻烦。

在Vue中通过原型链实现的这一功能。

只要在根组件注册了Provide,下面的所有子组件都能读到Provide传来的值。

使用Provide和Inject让根组件传值给后代组件

App.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<template>
<h1>App.vue(爷爷)</h1>
<label>
<input type="radio" value="red" name="color" v-model="colorVal">
红色
</label>
<label>
<input type="radio" value="green" name="color" v-model="colorVal">
绿色
</label>
<label>
<input type="radio" value="blue" name="color" v-model="colorVal">
蓝色
</label>
<div class="box"></div>
<hr>
<ProvideA></ProvideA>
</template>

<script setup lang="ts">
import { ref, provide, readonly } from "vue"
import ProvideA from '@/components/ProvideA.vue'
const colorVal = ref<string>("red")
// 把颜色值注入爷爷组件
// 参数1:注入名 参数2:变量
// 如果不想让子组件修改注入值,使用readonly包裹变量
// provide("color", colorVal)
provide("color", readonly(colorVal))
</script>

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

ProvideA.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template>
<div>
<h1>ProvideA.vue(父亲)</h1>
<div class="box"></div>
<hr>
<ProvideB></ProvideB>
</div>
</template>

<script setup lang="ts">
import { ref, inject } from 'vue'
import type { Ref } from 'vue'
import ProvideB from './ProvideB.vue'
// 父亲组件获取爷爷组件注入的值
// 参数1:注入名 参数2:默认值
const color = inject<Ref<string>>("color", ref("red"))
</script>

<style scoped lang="scss">
.box {
height: 50px;
width: 50px;
border: 1px solid #ccc;
// 在Vue3中,样式里可以使用v-bind绑定setup中的变量
background-color: v-bind(color);
}
</style>

ProvideB.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<template>
<div>
<h1>ProvideB.vue(孙子)</h1>
<div>
<!-- provide传的值可以被子组件修改 -->
<button @click="change">修改provide的值</button>
</div>
<div class="box"></div>
<hr>
</div>
</template>

<script setup lang="ts">
import { ref, inject } from 'vue'
import type { Ref } from 'vue'
// 孙子组件获取爷爷组件注入的值
const color = inject<Ref<string>>("color")

const change = ()=> {
// 不指定默认值时,color的类型:Ref<string> | undefined
// 非空断言
color!.value = "yellow"
}
</script>

<style scoped lang="scss">
.box {
height: 50px;
width: 50px;
border: 1px solid #ccc;
background-color: v-bind(color);
}
</style>

源码

在Vue源码(/package/runtime-core/src/apiInject.ts)中可以看到provide和inject的源码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// provide
export function provide<T, K = InjectionKey<T> | string | number>(
key: K,
value: K extends InjectionKey<infer V> ? V : T
) {
// 读取当前组件的实例(currentInstance)并做判断
if (!currentInstance) {
if (__DEV__) {
// 函数形式的provide只能在setup函数/语法糖模式使用,Options API无法使用
warn(`provide() can only be used inside setup().`)
}
} else {
// 读取当前组件实例中的provides
let provides = currentInstance.provides
// by default an instance inherits its parent's provides object
// but when it needs to provide values of its own, it creates its
// own provides object using parent provides object as prototype.
// this way in `inject` we can simply look up injections from direct
// parent and let the prototype chain do the work.
// 默认情况下,实例继承父类的provides对象
// 如果当前组件有自己的provide,它使用父provides对象作为原型创建自己的provides对象
// 在inject中,只需查询原型链即可

// 当前组件的父组件的provides
const parentProvides =
currentInstance.parent && currentInstance.parent.provides
// 判断父组件和子组件的provides是否一样
if (parentProvides === provides) {
// 如果一样的话(子组件还没有自己的provide),以父组件的provides为基础创建新对象
provides = currentInstance.provides = Object.create(parentProvides)
}
// TS doesn't allow symbol as index type
// 在新的对象上添加这次provide的值
provides[key as string] = value
}
}

// inject
// 一些函数重载
export function inject<T>(key: InjectionKey<T> | string): T | undefined
export function inject<T>(
key: InjectionKey<T> | string,
defaultValue: T,
treatDefaultAsFactory?: false
): T
export function inject<T>(
key: InjectionKey<T> | string,
defaultValue: T | (() => T),
treatDefaultAsFactory: true
): T
export function inject(
key: InjectionKey<any> | string,
defaultValue?: unknown,
treatDefaultAsFactory = false
) {
// fallback to `currentRenderingInstance` so that this can be called in
// a functional component
// 读取当前组件实例
const instance = currentInstance || currentRenderingInstance

// also support looking up from app-level provides w/ `app.runWithContext()`
// 如果能读到
if (instance || currentApp) {
// #2400
// to support `app.use` plugins,
// fallback to appContext's `provides` if the instance is at root
// 尝试去读父组件的provides,如果实例在根目录,回退到appContext的provides中
const provides = instance
? instance.parent == null
? instance.vnode.appContext && instance.vnode.appContext.provides
: instance.parent.provides
: currentApp!._context.provides

if (provides && (key as string | symbol) in provides) {
// TS doesn't allow symbol as index type
// 读到就直接返回
return provides[key as string]
} else if (arguments.length > 1) {
return treatDefaultAsFactory && isFunction(defaultValue)
? defaultValue.call(instance && instance.proxy)
: defaultValue
// 读不到就报错
} else if (__DEV__) {
warn(`injection "${String(key)}" not found.`)
}
} else if (__DEV__) {
warn(`inject() can only be used inside setup() or functional components.`)
}
}