Search code examples
inheritancevue.jslifecyclevue-class-components

Vue – Auto run function on component created


I'm using Vue CLI 3.x with TypeScript classes (.tsx files).

I want to implement permission handling for all of my views.

The simplest scenario would be: Routing to Component X; has access permission ? stay; has no permission ? route to default page.

I already implemented the logic for handling everything correctly, but I'm struggling at a good architecture.

For now I added my protected handler function to a Vue component ViewBase, and all my components that are also views, inherit this class and call this function in their created() lifecycle hook. It looks like this:

import Vue from 'vue';
import Component from 'vue-class-component';

@Component
class ViewBase extends Vue {
  protected handleAccess() {
    // route here
  }
}

@Component
class MyView extends ViewBase {
  private created() {
    this.handleAccess();
  }
}

But I don't like calling something in the created hook manually in each of my components. Can I somehow automate that?


Solution

  • You can use Mixins (TypeScript).

    Define your handle access code in the created hook in a mixin directly, and include (or extend in TypeScript) this mixin for all your view components. The hook will be merged to your view components, just as if you defined the hook in the view components.

    // mixin.ts
    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 {
      created () {
        // handle access code
      }
    }
    
    
    // my-view.ts
    import Component, { mixins } from 'vue-class-component'
    import MyMixin from './mixin.ts'
    
    @Component
    export class MyView extends mixins(MyMixin) {
    }