beforeEachグローバルフックはユーザーのアクセス権を管理します!

2523 ワード

ルーティングの作成:
export default new Router({
  routes: [{
     path: '/',
     component: { template: '
admin1 boos1
' } }, { path: '/login', name: 'HelloWorld', component: HelloWorld }, { path: '/admin1', meta: { roles: ['admin'] // }, component: { template: '
admin 1
' } }, { path: '/boos1', meta: { roles: ['boos'] // }, component: { template: '
boos 1
' }, }, { path: '*', component: { template: '
404
' } } ] })

ログインをシミュレートし、storageとstoreにユーザー情報を保存します.



import * as types from '@/store/types'
export default {
  data () {
    return {
    }
  },
  methods: {
  	login(u) {
  		let payload = {name: 'qqq', role: u, token: 'ncbnv'}
  		this.$store.commit(types.USER, payload)
  		var path = this.$route.query.redirect ? this.$route.query.redirect : '/';// 
  		this.$router.replace(path)
  	}
  }
}





main.js:
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'


Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router: router,
  store,
  components: { App },
  template: ''
})

router.beforeEach((to, from, next) => {
  // var user = localStorage.user ? JSON.parse(localStorage.user) : '';
  var user = store.state.user;
  if (user && user.token) { //  token
    if (to.meta.roles && to.meta.roles.indexOf(user.role) === -1) {// 
    	alert('403')
    	if(from.path == '/login'){
    		next('/')
    	}else{
    		next({path: from.path})
    	}
    } else {// 
    	next()
    }
  } else if(to.path != '/login'){// token , 
      next({path:'/login', query: {redirect: to.fullPath}})
  } else{
  	next()
  }
})