【问题标题】:Implement typescript generic in Vue mixin using class component使用类组件在 Vue mixin 中实现 typescript 泛型
【发布时间】:2020-10-15 17:36:12
【问题描述】:

我刚刚将我的 Vue 项目迁移到 Typescript,但是我需要处理一个缺失的情况。

我需要在我的应用程序中处理一些分页表,所以我创建了一个 Table mixin 来处理我的记录集合的分页:

@Component
export default class Table<T> extends Vue {
  records: T[] = []

  page: number = 0
  length: number = 20

  get total () {
    return this.records.length
  }

  get visibleRecords(): T[] {
    return this.records.slice(this.page*this.length, (this.page+1)*this.length)
  }

  public changePage (newPage: number) {
    this.page = newPage
  }
}

呈现表格、扩展 mixin、填充 records 属性并简单地显示 visibleRecords 计算属性的结果的每个组件。一个基本组件:

export default class Sampletable extends Mixins(Table) {

  records: RecordType[] = [ .... my data array ... ]
}

<template>
  <table>
    <tr v-for="record in visibleRecords">
      ....
    </tr>
  </table>
</template>

这行得通,但是通过调用“visibleRecords”,我失去了我的数据类型的知识(示例中为RecordType)。我需要让 typescript 了解 visibleRecords(在 mixin 中实现)返回与 records 属性相同的数据类型(在实现 thr mixin 的组件中被覆盖)

我尝试使用泛型实现Table mixin(如您在前面的代码中所见)但它不起作用,因为我无法在扩展 Mixin 时定义泛型类型:

export default class Sampletable extends Mixins(Table<RecordType>)

抛出错误。

有没有办法做到这一点?有什么建议吗?

【问题讨论】:

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


    【解决方案1】:

    尝试这样做:

    export default class Sampletable extends Mixins<Table<RecordType>>(Table) {
    ...
    

    来源:https://github.com/vuejs/vue-class-component/issues/289#issuecomment-471388618

    【讨论】:

    • 非常感谢您的回答。不幸的是,我得到'TS2315:'Vue'类型不是通用的。'错误
    猜你喜欢
    • 2021-12-22
    • 2019-12-08
    • 2017-08-22
    • 2020-06-11
    • 2014-08-19
    • 2018-07-07
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多