示例如下:(第一张图)当你点击车1的时候你写了路由守卫就点不开出现无权访问
(第二张图,就是可以访问后的图)有路由守卫点不开的情况下当你在本地存储中写了你在路由守卫中写的东西就可以进入了
你需要在router下的index.js中(以下代码有我写的路由页面不用管,看有注释的代码是路由守卫,通过你定义的"user=张三"的时候访问就会显示出来第二张图)
javascript
import Vue from 'vue'
import VueRouter from 'vue-router'
// import HomeView from '../views/HomeView.vue'
import CarView from '@/views/CarView.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'car',
component: CarView,
},
{
path: '/car',
name: 'car',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: CarView,
children: [
{
name: "/car/carone",
path: "carone",
// 这个是路由守卫
meta:{
isAuth:true,
},
component: () => import(/* webpackChunkName: "about" */ '../views/CarViewOne.vue')
},
{
name: "/car/cartwo",
path: "cartwo",
component: () => import(/* webpackChunkName: "about" */ '../views/CarViewTwo.vue')
},
{
name: "/car/carthree",
path: "carthree",
component: () => import(/* webpackChunkName: "about" */ '../views/CarViewThree.vue')
},
],
},
{
path: '/phone',
name: 'phone',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this routeb
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/PhoneView.vue')
},
]
const router = new VueRouter({
mode:'history',
base:process.env.BASE_URL,
routes
})
// 这个就是路由守卫看上面的路由页面中 CarView第一个车1 /car/carone的页面中 meta 就是和一下这段路由去写的
//全局前置路由守卫------------初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
// console.log(to,from);
//如果路由需要跳转
if (to.meta.isAuth) {
let user = localStorage.getItem('user')
if (user == '张三'){
next()
}else{
alert('无权访问')
}
} else {
// 否则,放行
next()
}
})
export default router