Check permissions before vue.js route loads

笑着哭i 提交于 2019-12-01 12:45:00

问题


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!


回答1:


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
    }
  }
}


来源:https://stackoverflow.com/questions/41785010/check-permissions-before-vue-js-route-loads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!