使用类组件在 Vue mixin 中实现 typescript 泛型

gba*_*zzi 0 typescript vue.js vue-class-components

我刚刚将我的 Vue 项目迁移到 Typescript,但有一种情况我需要管理。

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

@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
  }
}
Run Code Online (Sandbox Code Playgroud)

每个渲染表、扩展 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>
Run Code Online (Sandbox Code Playgroud)

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

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

export default class Sampletable extends Mixins(Table<RecordType>)
Run Code Online (Sandbox Code Playgroud)

抛出错误。

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

小智 5

尝试这样做:

export default class Sampletable extends Mixins<Table<RecordType>>(Table) {
...
Run Code Online (Sandbox Code Playgroud)

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