需求:在未登录的情况下,不能通过路由路径进入到页面;
import Vue from 'vue' import VueRouter from 'vue-router' import home from '@/views/home' import login from '@/views/pages/login.vue' import AssetPortrait from '@/views/pages/AssetPortrait .vue' Vue.use(VueRouter) const routes = [ { path: '/', redirect: '/login' }, { path: '/login', name: 'login', component: login }, { path: '/home', name: 'home', component: home, meta: { requireAuth: true }, children: [ { path: '/AssetPortrait', name: 'AssetPortrait', component:AssetPortrait, } ] ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) router.beforeEach((to, from, next) => { if (to.matched.some((r) => r.meta.requireAuth)) { let user = localStorage.user if (user) { // 判断是否已经登录 next() } else { next({ path: '/', query: { redirect: to.fullPath } // 登录成功后重定向到当前页面 }) } } else { next() } // 如果本地存在 token 则 不允许直接跳转到 登录页面 if (to.fullPath === '/login') { if (localStorage.user) { next({ path: '/home' }) } else { next() } } }) export default router