【问题标题】:Mixin that uses component properties (Vue 2, TypeScript)使用组件属性的 Mixin(Vue 2、TypeScript)
【发布时间】:2021-10-05 19:56:04
【问题描述】:

我有Vue + TypeScript 项目,我们正在使用Vue class components。组件的方法之一被移动到单独的 mixin。该 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”。 属性“加载”在“PageVouchersTable”类型中是私有的,但在“ExpSelectedHandlerMixin”类型中不是私有的。

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

这行得通。

但是:

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

【问题讨论】:

    标签: typescript vue.js vuejs2 vue-mixin


    【解决方案1】:

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

    // Mixin
    @Component({})
    export default class ExpSelectedHandlerMixin extends Vue {
      loading = false
    
      items: VouchersPoolTable[] = []
    
      selected: VouchersPoolTable[] = []
    
      // ...
    }
    
    // Component
    import { Mixins } from 'vue-property-decorator';
    
    @Component({})
    export default class PageVouchersTable extends Mixins(ExpSelectedHandlerMixin) {
    
      // Next three properties are public to be accessible in ExpSelectedHandlerMixin
      loading = false
    
      items: VouchersPoolTable[] = []
    
      selected: VouchersPoolTable[] = []
    
      // ...
    }
    
    

    【讨论】:

      猜你喜欢
      • 2020-10-15
      • 2019-12-05
      • 2020-05-04
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2017-04-07
      • 2021-03-15
      相关资源
      最近更新 更多