什么是 Vue 3 组合 API 定义方法的类型安全方式 [英] What's Vue 3 composition API's type-safe way of defining methods

查看:38
本文介绍了什么是 Vue 3 组合 API 定义方法的类型安全方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Vue 的组合 API(在 Vue.js 3 中)并主要在 setup() 中构建我的组件逻辑.虽然 访问我自己的 props 通过 setup(props) 很简单,我无法将此处定义的函数公开为 methods 以类型安全的方式.

I'm using Vue's composition API (in Vue.js 3) and build my component logic mostly within setup(). While accessing my own props via setup(props) is straight forward, I'm unable to expose the functions defined here as methods in a type-safe manner.

以下有效,但我需要任意转换,因为没有暴露给 TypeScript 的方法接口.

The following works, but I need the any-cast, since there's no method interface exposed to 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 中定义我的函数不是一种选择,因为那样的话,我将无法从设置中访问它.

Defining my function in methods is not an option, since that way, I wouldn't be able to access it from setup.

推荐答案

您正在寻找 InstanceType.

You're looking for InstanceType.

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 };
  }
});

这种方法的一个警告是(如您所见)您必须使用 可选链非空断言运算符,除非您将初始/默认实例作为参数传递给 ref() 函数;否则,TypeScript 会将其标记为可能未定义".

One caveat with this approach is that (as you can see) you'd have to use an optional chaining or non-null assertion operator, unless you pass an initial/default instance as an argument to the ref() function; otherwise, TypeScript is going to mark it as "possibly undefined".

在大多数情况下,如果您确定它总是会被定义,您可以使用 as-语法.

In most cases, if you are certain that it's always going to be defined, you could type cast it to an empty object with the as-syntax.

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

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

这篇关于什么是 Vue 3 组合 API 定义方法的类型安全方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆