[英]How to annotate a variable in Vue as a Vue component when using Typescript?
I'm using VueJS and Typescript and I am not using Class-Style Vue Components.我正在使用 VueJS 和 Typescript,我没有使用类样式的 Vue 组件。
Say I have the following Vue component.假设我有以下 Vue 组件。
<template>
<my-component ref="component"/>
</template>
<script lang="ts">
import MyComponent from "@/components/my-component.vue";
export default Vue.extend({
components: {
MyComponent,
},
methods: {
async someMethod() {
// How do I annotate the following component variable as type "MyComponent"?
const component = this.$refs["component"];
console.log(component.$props);
},
},
});
</script>
How do I annotate the component
variable in the someMethod
method properly so that the Typescript compiler is aware of properties like $props
etc.?如何正确注释
someMethod
方法中的component
变量,以便 Typescript 编译器知道$props
等属性?
The following (which was my initial instinct) does not work.以下(这是我最初的直觉)不起作用。
const component: MyComponent = this.$refs["component"];
in vue+vscode ecosystem, now typescript cannot infer type from template declaration.在 vue+vscode 生态系统中,现在 typescript 无法从模板声明中推断类型。 (maybe it will be)
(也许会)
and for $refs[xxx]:对于 $refs[xxx]:
Type 'Vue |输入'Vue | Element |
元素 | Vue[] |
Vue[] | Element[]' is not assignable to type 'Vue'.
Element[]' 不可分配给类型 'Vue'。
you can use type assertions instead:您可以改用类型断言:
const component = this.$refs["component"] as typeof MyComponent; const component = this.$refs["component"] as typeof MyComponent;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.