1.首先创建一个types.ts文件,放入注入的相关代码,比如注入用户相关信息:
import { provide, inject, InjectionKey, reactive } from 'vue';
export type AccountInfo = {
uid?: number;
userName?:string;
};
export const SYMBOL_ACCOUNT = Symbol("user") as InjectionKey<AccountInfo>;
export const useInjectAccount = () => {
return inject(SYMBOL_ACCOUNT)!;
};
export const useProvideAccount = (user:AccountInfo) => {
const value = reactive(user);
provide(SYMBOL_ACCOUNT, value);
return value;
};
2.在父组件中使用:
import { useProvideAccount } from '../types'
...
const user = reactive({
uid:1,
userName:'zlp'
})
useProvideAccount(user)
3.在子组件中:
<span>{{user.userName}}</span>
import { useInjectAccount } from '../types'
const user=useInjectAccount()