vue 路由權限

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import login from '@/components/login'
import register from '@/components/register'
Vue.use(Router)

const router = new Router({
 mode: 'history',
 routes: [{
   path: '/',
   name: 'home',
   component: HelloWorld,
   meta: {
    requiresAuth: true
   }
  },
  {
   path: '/HelloWorld',
   name: 'HelloWorld',
   component: HelloWorld,
  },
  {
   path: '/login',
   name: 'login',
   component: login,
  },
  {
   path: '/register',
   name: 'register',
   component: register,
  },
 ]
});

//註冊全局鉤子用來攔截導航
router.beforeEach((to, from, next) => {
 //獲取store裏面的token
 let token = store.state.token;
 //判斷要去的路由有沒有requiresAuth
 if (to.meta.requiresAuth) {
  if (token) {
   next();
  } else {
   next({
    path: '/login',
    query: { redirect: to.fullPath } // 將剛剛要去的路由path做爲參數,方便登陸成功後直接跳轉到該路由
   });
  }
 } else {
  next(); 
 }
});
export default router;
相關文章
相關標籤/搜索