Trung Tran
Trung Tran

Reputation: 13741

Check permissions before vue.js route loads

does anyone know how to check a user's permissions before a vue.js route is rendered? I came up with a partial solution by checking permissions in the created stage of a component:

created: function () {

    var self = this;

    checkPermissions(function (result) {
        if(result === 'allowed') {
            // start making AJAX requests to return data
            console.log('permission allowed!');
        } else {
            console.log('permission denied!');
            self.$router.go('/denied');
        }   
    });
}

However, the issue is the entire page loads momentarily (albeit without any data) before the checkPermission() function gets activated and re-routes to /denied.

I also tried adding the same code in the beforeCreate() hook, but it didnt seem to have any effect.

Does anyone else have any other ideas? Note - the permissions vary from page to page.

Thanks in advance!

Upvotes: 1

Views: 6989

Answers (1)

Belmin Bedak
Belmin Bedak

Reputation: 9201

The thing you need is defined in Vue Router Docs as Data Fetching - https://router.vuejs.org/en/advanced/data-fetching.html

So, as docs says, sometimes you need to fetch data when route is activated.

Keep checkPermissions in created hook, and then watch the route object:

watch: {
  // call again the method if the route changes
  '$route': 'checkPermissions'
}

A maybe more handy solution would be move logic from created hook into separated method and then call it in hook and in watch object too, as well.(Using ES6 syntax bellow)

export default {
  created() {
    this.checkPermissions()
  },
  watch: {
   '$route': 'checkPermissions'
  },
  methods: {
    checkPermissions() {
      // logic here
    }
  }
}

Upvotes: 1

Related Questions