typescriptvue.jsvue-mixinvue-property-decorator

Using vue mixin inside @Component


I'm using vue-property-decorator package and I want to use mixin method inside beforeRouteEnter hook.

What I did:

import { Component, Mixins } from 'vue-property-decorator';
import { myMixin } from '../mixins';

@Component({})
export default class myClass extends Mixins(myMixin) {
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.callMixinMethod();
    })
  }
}

This has a problem, as to, from, next and vm do not get assigned their respective types automatically.

So what I need to do is place beforeRouteEnter into @Component

@Component({
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.callMixinMethod();
    })
  }
})

This solves the problem of types, they are picked up automatically. But this poses another problem. Inside @Component mixin method is not defined. It says

Property 'callMixinMethod' does not exist on type 'Vue'

I tried to register mixins inside @Component like this:

@Component({
  mixins: [myMixin],
  beforeRouteEnter...
})

But that didn't help.

Is there some way to make beforeRouteEnter hook inside @Component see the methods of imported mixins somehow? Maybe extend vm with mixins somehow?


Solution

  • What I found out is that we can assign type to vm manually like so:

    @Component({
    beforeRouteEnter(to, from, next) {
        next(vm: myClass & myMixin => {
          vm.callMixinMethod();
        })
      }
    })
    export default class myClass extends Mixins(myMixin) {
    }
    

    And myMixin looks like this:

    @Component({})
    export default class myMixin extends Vue {
      public callMixinMethod() {
        // do smth
      }
    }