1

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?

1 Answer 1

2

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) {
}
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice! Although it seems that I need to do my created() hook protected in my mixin class, so I am still able to use it in my child components. But that's no big deal for me. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.