什么是 Vue 3 组合 API 定义方法的类型安全方式
What's Vue 3 composition API's type-safe way of defining methods
我正在使用 Vue 的组合 API(在 Vue.js 3 中)并主要在 setup()
中构建我的组件逻辑。而 accessing my own props via setup(props)
is straight forward, I'm unable to expose the functions defined here as 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
。
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 };
}
});
这种方法的一个警告是(如您所见)您必须使用 optional chaining or non-null assertion operator,除非您将 initial/default 实例作为参数传递给 ref()
功能;否则,TypeScript 会将其标记为“可能未定义”。
在大多数情况下,如果您确定它总是会被定义,您可以使用 as
-syntax.
将其类型转换为一个空对象
const my = ref({} as InstanceType<typeof MyComponent>);
async func() {
await my.value.publicFunction();
}
我正在使用 Vue 的组合 API(在 Vue.js 3 中)并主要在 setup()
中构建我的组件逻辑。而 accessing my own props via setup(props)
is straight forward, I'm unable to expose the functions defined here as 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
。
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 };
}
});
这种方法的一个警告是(如您所见)您必须使用 optional chaining or non-null assertion operator,除非您将 initial/default 实例作为参数传递给 ref()
功能;否则,TypeScript 会将其标记为“可能未定义”。
在大多数情况下,如果您确定它总是会被定义,您可以使用 as
-syntax.
const my = ref({} as InstanceType<typeof MyComponent>);
async func() {
await my.value.publicFunction();
}