Skip to content

Commit

Permalink
feat: Support component options mixin (#2)
Browse files Browse the repository at this point in the history
* feat: make mixins function argument variadic

* feat: support component options object mixins
  • Loading branch information
ktsn committed Nov 11, 2019
1 parent 2923163 commit ffd2f8c
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 12 deletions.
28 changes: 17 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
import Vue, { VueConstructor } from 'vue'
import Vue, { VueConstructor, ComponentOptions } from 'vue'

export type VueClass<T> = VueConstructor<T & Vue>
type VueMixin = VueConstructor | ComponentOptions<never>

type UnionToIntersection<U> = (U extends any
? (k: U) => void
: never) extends (k: infer I) => void
? I
: never

export type MixedVueConstructor<
Ctors extends VueConstructor[]
> = Ctors extends VueConstructor<infer Vs>[]
? VueClass<UnionToIntersection<Vs>>
type ExtractInstance<T> = T extends VueConstructor<infer V>
? V
: T extends ComponentOptions<infer V>
? V
: never

export default function mixins<Ctors extends VueConstructor[]>(
...Ctors: Ctors
): MixedVueConstructor<Ctors>
export default function mixins(...Ctors: VueConstructor[]): VueConstructor {
return Vue.extend({ mixins: Ctors })
type MixedVueConstructor<Mixins extends VueMixin[]> = Mixins extends (infer T)[]
? VueConstructor<UnionToIntersection<ExtractInstance<T>> & Vue>
: never

export default function mixins<Mixins extends VueMixin[]>(
...mixins: Mixins
): MixedVueConstructor<Mixins>
export default function mixins(
...mixins: (VueConstructor | ComponentOptions<Vue>)[]
): VueConstructor {
return Vue.extend({ mixins })
}
44 changes: 43 additions & 1 deletion test/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as assert from 'power-assert'
import Vue from 'vue'
import Vue, { ComponentOptions } from 'vue'
import mixins from '../src/index'

Vue.config.productionTip = false
Expand Down Expand Up @@ -43,4 +43,46 @@ describe('mixins', () => {
assert(vm.value === true)
assert(vm.concat === 'test 123 true')
})

it('allow component options object mixins', () => {
const Foo = Vue.extend({
data() {
return {
foo: 'test'
}
}
})

interface BarInstance extends Vue {
bar: number
}

const Bar: ComponentOptions<BarInstance> = {
data() {
return {
bar: 123
}
}
}

const App = mixins(Foo, Bar).extend({
data() {
return {
value: true
}
},

computed: {
concat(): string {
return `${this.foo} ${this.bar} ${this.value}`
}
}
})

const vm = new App()
assert(vm.foo === 'test')
assert(vm.bar === 123)
assert(vm.value === true)
assert(vm.concat === 'test 123 true')
})
})

0 comments on commit ffd2f8c

Please sign in to comment.