什么是 Vue 3 组合 API 定义方法的类型安全方式

2024-04-06

我正在使用 Vue 的组合 API(在 Vue.js 3 中)并主要在内部构建我的组件逻辑setup(). While 访问我自己的道具 https://v3.vuejs.org/guide/composition-api-setup.html#props via setup(props)很简单,我无法将此处定义的函数公开为methods https://v3.vuejs.org/guide/data-methods.html#methods以类型安全的方式。

以下内容有效,但我需要任意转换,因为没有向 TypeScript 公开的方法接口。

<!-- MyComponent.vue -->

<script lang='ts'>
// ...
export default defineComponent({
  setup() {
    // ...
    return {
       publicFunction: async (): Promise<void> => { /* ... */ };
    }
  }
});

</script>
<!-- AppComponent.vue -->

<template>
  <MyComponent ref="my"/>
</template>

<script lang='ts'>

export default defineComponent({
  async setup() {
    const my = ref();

    async func() {
      await (my.value as any).publicFunction(); // <-- gross!
    }

    return { my, func };
  }
});

</script>

定义我的函数methods不是一个选项,因为这样,我将无法从设置中访问它。


您正在寻找InstanceType https://www.typescriptlang.org/docs/handbook/utility-types.html#instancetypetype.

import MyComponent from 'path/to/the/component';

export default defineComponent({
  async setup() {
    const my = ref<InstanceType<typeof MyComponent>>();

    async func() {
      await my.value?.publicFunction();
    }

    return { my, func };
  }
});

这种方法的一个警告是(如您所见)您必须使用可选链接 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html or 非空断言运算符 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator,除非您将初始/默认实例作为参数传递给ref()功能;否则,TypeScript 会将其标记为“可能未定义".

在大多数情况下,如果您确定它总是会被定义,您可以使用以下命令将其强制转换为空对象:as-syntax https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions.

const my = ref({} as InstanceType<typeof MyComponent>);

async func() {
  await my.value.publicFunction();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

什么是 Vue 3 组合 API 定义方法的类型安全方式 的相关文章

随机推荐