Typescript 无法识别 Vue 组件上的 prop 值

标签 typescript vue.js vuejs2

我有以下 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 推断所有 propsprop 时丢失类型为 {} .这里的区别是你有一个 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[]>,
  }
})

screencast demo


更新 这是fixed在 Vue 中 2.6.0 .

关于Typescript 无法识别 Vue 组件上的 prop 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54391162/

相关文章:

angular - 如果数据加载仍在使用 rxjs 进行,如何返回数据或等待

typescript - Typescript 中通用容器的混淆错误

node.js - VSCODE 构建错误 `The terminal process "/bin/zsh '-c' , 'yarn run watch-extensionsd' "无法启动(退出代码 : 127). `

vue.js - 组件中的 $on 监听器可以监听来自 mixin 的 $emit 吗?

javascript - VueJS 访问嵌套组件数据值

html - 如何使用 WebView 加载 Google Play 页面?

javascript - 多条件过滤

vue.js - webpack运行构建但不退出命令

node.js - 使用带有 vue js 的快速 Handlebars

javascript - vue 中对象属性变为空白