使用组件属性的 MixinVue 2、TypeScript

问题描述

我有 Vue + TypeScript 项目,我们正在使用 Vue class components。组件的方法之一被移动到单独的混合。该 mixin 使用组件的属性。为了防止 TypeScript 抱怨缺少 mixin 属性,我创建了与 mixin 同名的接口:

export interface ExpSelectedHandlerMixin {
  loading: boolean;
  selected: VouchersPoolTable[];
  currentApplication: string;
  items: VouchersPoolTable[];
}

@Component({})
export class ExpSelectedHandlerMixin extends Vue {
   // ...
}

然后像这样将 mixin 连接到我的组件:

import { Mixins } from 'vue-property-decorator';

export default class PageVouchersTable extends Mixins(ExpSelectedHandlerMixin) {
   // ...
}

之后我收到文本错误

“PageVouchersTable”类错误地扩展了基类“ExpSelectedHandlerMixin & Vue & object & Record”。 “PageVouchersTable”类型不可分配给“ExpSelectedHandlerMixin”类型。 属性“loading”在“PageVouchersTable”类型中是私有的,但在“ExpSelectedHandlerMixin”类型中不是。

好的,我在组件 loading 中创建了 selectedcurrentApplicationitemspublic 属性(只是删除private 修饰符)。

那行得通。

但是:

是否有可能以某种方式连接使用组件属性的 mixin 而不使这些属性 public

解决方法

决定去掉mixin文件中不必要的接口声明,在组件中保留共享属性为static_assert。最终版本的代码是:

#include <type_traits>

template<class T>
auto type() { return std::declval<T>(); }

using T = decltype(type<int>());