Vue2+TS项目使用依赖组件属性的Mixin能否不将对应属性设为public
问题原因
该报错本质是TypeScript访问修饰符的类型匹配规则:
- 父类/接口中声明的public属性,子类实现时不能使用更严格的访问级别(private/protected)
- private属性仅允许在声明它的类内部访问,混入的mixin不属于当前组件类本身,无法直接访问私有属性
不存在能让mixin直接访问组件private属性的方案,以下是两种满足封装要求的替代实现:
方案1:使用protected抽象属性(推荐)
抛弃原先的同名接口声明方式,直接将mixin定义为抽象类,在类内部声明protected级别的抽象属性要求,组件对应属性也使用protected修饰即可,既不需要暴露为public,也能满足mixin的访问需求:
// mixin定义 @Component({}) export default abstract class ExpSelectedHandlerMixin extends Vue { // 声明子类必须提供的protected属性 protected abstract loading: boolean; protected abstract selected: VouchersPoolTable[]; protected abstract currentApplication: string; protected abstract items: VouchersPoolTable[]; // mixin原有方法可以直接访问以上protected属性 }
// 组件实现 import { Mixins } from 'vue-property-decorator'; export default class PageVouchersTable extends Mixins(ExpSelectedHandlerMixin) { // 用protected替代private,仅类内部和子类/mixin可访问,外部不可访问 protected loading = false; protected selected: VouchersPoolTable[] = []; protected currentApplication = ''; protected items: VouchersPoolTable[] = []; }
方案2:通过取值方法封装私有属性
如果必须保留属性的private修饰符,可以在mixin中声明一个抽象取值方法,由组件实现该方法返回私有属性,mixin通过调用方法获取需要的值即可:
// mixin定义 @Component({}) export default abstract class ExpSelectedHandlerMixin extends Vue { // 声明子类必须实现的取值方法 protected abstract getSelectionDeps(): { loading: boolean; selected: VouchersPoolTable[]; currentApplication: string; items: VouchersPoolTable[]; }; handleSelection() { // 调用取值方法获取所需属性,不需要直接访问组件私有属性 const { loading, selected, currentApplication, items } = this.getSelectionDeps(); // 原有逻辑 } }
// 组件实现 import { Mixins } from 'vue-property-decorator'; export default class PageVouchersTable extends Mixins(ExpSelectedHandlerMixin) { // 保留private修饰符 private loading = false; private selected: VouchersPoolTable[] = []; private currentApplication = ''; private items: VouchersPoolTable[] = []; // 实现取值方法返回私有属性 protected getSelectionDeps() { return { loading: this.loading, selected: this.selected, currentApplication: this.currentApplication, items: this.items } } }
内容的提问来源于stack exchange,提问作者Eduardo
相关产品推荐
相关产品推荐

