Vue3 provide inject 正常使用方式
父页面通过 provide
注入对象信息,子页面通过 inject
获取对象信息。
可以通过 injectKey
来保存类型,避免上下文丢失问题。
1 2 3 4 5 6 7 8 9
| 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
| 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
| import { userInfoKey, UserInfo } from '@/composables/userInfoKey'
const userInfo1 = inject('userInfo')
const userInfo2 = inject(userInfoKey)
|