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>
Logo

前往低代码交流专区

更多推荐