vue3 + Ts provide 和 inject 使用
provide(‘abc’, {name: editId,});对象的类型为 “unknown”const abc = inject(‘abc’, { name: 0 });console.log(‘abc’, abc);
·
Ts 提示对象的类型为 “unknown”
provide/inject 只适用于最外层
方案1 使用默认值 (有小问题)
如果是 ref 不要加 .value
provide('abc', {
name: editId,
});
const abc = inject('abc', { name: 0 });
console.log('abc', abc);
方案2 使用 InjectionKey 推荐
type.ts
import { InjectionKey, Ref } from 'vue';
export interface Params {
name: string;
}
export const paramsKey: InjectionKey<Ref<Params>> = Symbol('');
export type setParams = (params: Params) => void;
export const setParamsKey: InjectionKey<setParams> = Symbol('');
父
import { paramsKey, setParamsKey, Params } from './type';
const user = ref({ name: 'zs' });
provide(paramsKey, user);
function setUser(params: Params) {
user.value.name = params.name;
}
provide(setParamsKey, setUser);
子
<div @click="handleClick">{{ user }}</div>
<script lang="ts" setup>
import { inject } from 'vue';
import { paramsKey, setParamsKey } from './type';
const user = inject(paramsKey);
const setUser = inject(setParamsKey);
console.log('user', user);
function handleClick() {
setUser?.({ name: 'ls' });
}
</script>
更多推荐
已为社区贡献8条内容
所有评论(0)