Vue——路由定义及基本使用

Vue.use(VueRouter)

/**定义路由**/
const routes = [
  {
    path: '/',
    component: login
  },
  {
    path: '/login',
    name :'login',
    component: login
  },
  { path: '*', component: notfound },/*url路径跟路由跳转不匹配,404*/
  {
    path: '/table',
    component: table,
      meta: {
               requireAuth: true,  // 添加该字段,表示进入这个路由是需要登录的
          },
    children: [
      {
        path: '/',
        component: batteryFactory
      },
      {
        path: 'batteryFactory',
        component: batteryFactory
      },
      {
        path: 'batteryManage',
        component: batteryManage
      }
    ]
  }


];
// 页面刷新时,重新赋值token
if (window.sessionStorage.getItem('token')) {
  store.commit(types.LOGIN, window.sessionStorage.getItem('token'))
}

const router = new VueRouter({
  mode: 'history',
  routes: routes
});

router.beforeEach((to, from, next) => {
  debugger

  if (to.matched.some(r => r.meta.requireAuth)) {// 判断该路由是否需要登录权限
    if (store.state.token) {// 通过vuex state获取当前的token是否存在
      next();
    }
    else {
      next({
        path: '/login',
        query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
      })
    }
  }
  else {
    next();
  }
})

你可能感兴趣的:(Vue——路由定义及基本使用)