我有以下 Vue 组件。它的目的是构建一个通用的侧边栏,该侧边栏使用不同的数据两次或三次
<template>
<div>
<h5>{{ title }}</h5>
<div v-for="prop of data" :key="prop.id">
<router-link :to="path(prop.id)">{{ prop.name }}
<i class="material-icons right">edit</i></router-link>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue';
export default Vue.extend({
props: {
data: Array,
title: String,
pathbase: String
},
methods: {
path(id): string {
return `${this.$props.pathbase}/${id}`;
}
}
});
</script>
我的问题是这样的。为什么我必须使用 this.$props.pathbase
来访问这里的 pathbase
值?为什么 this.pathbase
被 Typescript 视为“无效”?这不是我第一次尝试在没有 $props
的情况下访问 Prop ,但这是 Typescript 第一次提示它。此外,如果我使用 this.pathbase
,Typescript 在我的编辑器 (VSCode) 中会报错,但 Vue 编译时没有错误,项目和组件会正确显示和运行。
VSCode 上的消息说:属性“pathbase”在类型“Vue”上不存在。
我想知道为什么会导致这个错误,因为我想更好地理解 typescript 。为什么 this.pathbase
会导致 typescript 提示,即使它不是编译错误?为什么我需要使用 $props
?
最佳答案
通常,您不需要使用 $props
.该问题类似于 known Vue/TypeScript issue ,其中 TypeScript 推断所有 props
在 prop
时丢失类型为 {}
.这里的区别是你有一个 prop
与类型 Array
(即 data: Array
)导致同样的问题,阻止访问 this.pathbase
.
解决方法是声明 Array
输入 as () => Foo[]
(或 as PropType<Foo[]>
对于版本 2.6 或更高版本),其中 Foo
是每个 data
的预期类型项目:
import Vue from 'vue'
export default new Vue.extend({
props: {
data: Array as () => string[],
}
})
或者:
// PropType added in version 2.6
import Vue, { PropType } from 'vue'
export default new Vue.extend({
props: {
data: Array as PropType<string[]>,
}
})
关于Typescript 无法识别 Vue 组件上的 prop 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54391162/