Vue3 provide inject 正常使用方式

父页面通过 provide 注入对象信息,子页面通过 inject 获取对象信息。

可以通过 injectKey 来保存类型,避免上下文丢失问题。

1
2
3
4
5
6
7
8
9
// userInfoKey.ts
import { InjectionKey } from 'vue'

export interface UserInfo {
id: Number
name: String
}

export const userInfoKey: InjectionKey<UserInfo> = Symbol()
1
2
3
4
5
6
7
8
9
10
11
12
13
// Parent.vue
import { userInfoKey, UserInfo } from '@/composables/userInfoKey'

provide(userInfoKey, {
id: 1,
name: 'test',
})

const userInfo: UserInfo = {
id: 1,
name: 'test',
}
provide('userInfo', userInfo)
1
2
3
4
5
6
7
// Child.vue
import { userInfoKey, UserInfo } from '@/composables/userInfoKey'
// 丢失上下文的对象
const userInfo1 = inject('userInfo')

// 保留了对象的类型
const userInfo2 = inject(userInfoKey)