【问题标题】:Typescript won't recognize prop values on Vue componentTypescript 无法识别 Vue 组件上的 prop 值
【发布时间】:2019-01-27 17:56:48
【问题描述】:

我有以下 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 的情况下访问道具,但这是 Typescript 第一次抱怨它。此外,如果我使用this.pathbase,Typescript 会在我的编辑器 (VSCode) 中报错,但 Vue 编译项目时不会出错,并且组件会显示并正常运行。

VSCode 上的消息说:Property 'pathbase' does not exist on type 'Vue'.

我想知道它为什么会导致这个错误,因为我想更好地理解 typescript。为什么this.pathbase 会导致打字稿抱怨,即使它不是编译错误?为什么我必须使用$props

【问题讨论】:

    标签: typescript vue.js vuejs2


    【解决方案1】:

    通常,您不需要使用$props。该问题类似于known Vue/TypeScript issue,当prop 的类型为{} 时,所有props 的TypeScript 推理都会丢失。这里的区别是你有一个prop 类型为Array(即data: Array)会导致同样的问题,阻止访问this.pathbase

    解决方法是用as () =&gt; Foo[](或as PropType&lt;Foo[]&gt; 2.6 或更高版本)声明Array 类型,其中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[]>,
      }
    })
    


    更新 这是 Vue 中的 fixed 2.6.0

    【讨论】:

      【解决方案2】:

      道具是只读的,这意味着孩子不是该特定数据的所有者,因此它不能更改该数据上的任何内容。 Pathbase 是你的道具中的一个属性,要访问该属性,你需要使用“this.props”来调用你的道具。

      【讨论】:

        猜你喜欢
        • 2017-08-19
        • 2021-03-30
        • 2018-07-13
        • 2020-04-17
        • 2020-11-14
        • 2021-05-20
        • 2020-11-15
        • 2020-02-06
        • 2013-04-04
        相关资源
        最近更新 更多