【发布时间】:2020-08-13 20:12:06
【问题描述】:
我已经使用 Vue 工作了一段时间,但已经开始转向使用 Typescript 实现。我遇到了一个问题,我无法通过父级的引用访问子级的方法。
父代码:
<template>
<ref-test ref="child"/>
</template>
<script lang="ts">
import Vue from "vue";
import RefTest from "./RefTest.vue";
export default Vue.extend({
name: "RefParent",
components: {
RefTest
},
data: () => ({}),
methods: {},
mounted() {
const child = this.$refs.child as RefTest;
child.pingMe();
}
});
</script>
<style scoped></style>
子代码:
<template>
<div>REF TEST...</div>
</template>
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
name: "RefTest",
data: () => ({}),
methods: {
pingMe() {
console.log("refTest pingMe");
}
}
});
</script>
<style scoped></style>
我看到的问题是,当我使用 const child = this.$refs.child as RefTest; 引用孩子时,我看到了错误:'RefTest' refers to a value, but is being used as a type here.。此外,child.pingMe(); 正在报告:Property 'pingMe' does not exist on type 'Vue'.
我尝试了各种变通方法:https://github.com/vuejs/vue/issues/8406 主要围绕接口定义和 Vue.extend<> 调用。
感谢任何帮助我继续思考使用 Typescript 的差异。
【问题讨论】:
-
错误说明出了什么问题。
RefTest既不是类型也不是接口,因此不能在需要类型的地方使用。试试as typeof RefTest。 -
谢谢。我想对 Typescript 较新,我不理解错误?使用
as typeof RefTest会产生新的错误。TS2352: Conversion of type 'Vue | Element | Vue[] | Element[]' to type 'VueConstructor<Vue>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type 'Element[]' is missing the following properties from type 'VueConstructor<Vue>': extend, nextTick, set, delete, and 8 more.
标签: typescript vue.js vue-component