vue-class-components mixins使用问题记录

1,042 阅读1分钟

1.vue-class-component提供了mixinshelper函数,以类样式的方式使用mixins。通过使用mixins帮助程序,TypeScript可以推断mixin类型并在组件类型上继承它们。

编写mixin的示例:

// mixin.js
import Vue from 'vue'
import Component from 'vue-class-component'

// You can declare a mixin as the same style as components.
@Component
export default class MyMixin extends Vue {
  mixinValue = 'Hello'
}

使用mixin:

import Component, { mixins } from 'vue-class-component'
import MyMixin from './mixin.js'

// Use `mixins` helper function instead of `Vue`.
// `mixins` can receive any number of arguments.
@Component
export class MyComp extends mixins(MyMixin) {
  created () {
    console.log(this.mixinValue) // -> Hello
  }
}

同时使用多个mixin:

import Component, { mixins } from 'vue-class-component'
import MyMixin1 from './mixin1.js'
import MyMixin2 from './mixin2.js'

// Use `mixins` helper function instead of `Vue`.
// `mixins` can receive any number of arguments.
@Component
export class MyComp extends mixins(MyMixin1MyMixin2) {
  created () {
  }
}

typescript 需要传入泛型的时候,同时使用多个mixin:

interface MyMixin1Type {}

interface MyMixin2Type {}

import Component, { mixins } from 'vue-class-component'
import MyMixin1 from './mixin1.ts'
import MyMixin2 from './mixin2.ts'

// Use `mixins` helper function instead of `Vue`.
// `mixins` can receive any number of arguments.
@Component
export class MyComp extends mixins<MyMixin1Type, MyMixin2Type>(MyMixin1, MyMixin2) {
  created () {
  }
}