【问题标题】:typing prop in Vue class-based component in typescript在打字稿中的基于 Vue 类的组件中键入 prop
【发布时间】:2020-03-23 04:42:03
【问题描述】:

在打字稿上下文中处理基于类的组件,并想知道我一直遇到的打字稿错误。

以下是我的组件代码:

<template>
  <b-message :type="statusToBuefyClass">
    <p>PLACEHOLDER</p>
  </b-message>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
@Component({
  components: {},
  props: {       <----------------- typed prop
    status: {
      type: String,
      required: false
    }
  }
})
export default class Foo extends Vue {

  // explicitly type status
  status!: string         <----------------- explicit, redundant typing

  get statusToBuefyClass(): string {
    const statusHash: {
      init: string
      active: string
      inactive: string
      archived: string
    } = {
      init: 'is-warning',
      active: 'is-success',
      inactive: '',
      archived: 'is-danger'
    }

    // return statusHash
    return Object(statusHash)[this.status]  <------ error is triggered by this
  }

  bar = this.status <------------- this would also error, if not explicitly typed above

  mounted() {}
}
</script>

以上工作没有编译错误。但是,如果我删除 status -- status!: string 的显式输入 -- 我会收到以下错误:

Property 'status' does not exist on type 'Foo'.

我发现了许多类似的文章和问题,但似乎没有一个完全符合我的情况。在我的tsconfig.json 中,我有以下一组,建议的一些帖子可能会有所帮助:

"strict": true,
"noImplicitThis": true,

有什么想法或见解吗?除了传递道具然后在export default class Foo extends Vue {... 中再次输入它们之外,还有其他方法吗?

【问题讨论】:

    标签: typescript vue.js vue-component vue-class-components


    【解决方案1】:

    我不完全确定我是怎么错过的,或者这感觉如何可持续,但我找到了解决方案。

    诀窍是使用 @Prop 装饰器。以下编译没有错误:

    <script lang="ts">
    import { Component, Prop, Vue } from 'vue-property-decorator'
    @Component({
      components: {}
    
      // <--------------- props removed from here...
    
    })
    export default class Foo extends Vue {
    
      @Prop(String) status!: string // <--------- use @Prop decorator to type and capture prop from parent
    
      get statusToBuefyClass(): string {
        const statusHash: {
          init: string
          active: string
          inactive: string
          archived: string
        } = {
          init: 'is-warning',
          active: 'is-success',
          inactive: '',
          archived: 'is-danger'
        }
    
        // return statusHash
        return Object(statusHash)[this.status] // <------- no more compilation errors here
      }
    
      mounted() {}
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 2019-12-01
      • 2019-10-04
      • 1970-01-01
      • 2021-01-09
      • 2020-08-27
      • 2020-07-08
      • 2019-07-15
      • 2020-10-14
      相关资源
      最近更新 更多