1. 安装并使用Vue Router
2. 定义路由表
3. 在路由表中添加路由守卫
4. 在路由守卫中进行权限判断
1. 安装并使用Vue Router
npm install vue-router --save
在main.js中引入Vue Router并使用:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
// 路由表
]
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
2. 定义路由表
在路由表中定义需要进行权限控制的路由,例如:
const routes = [
{
path: '/home',
component: Home
},
{
path: '/admin',
component: Admin,
meta: {
requiresAuth: true // 需要登录才能访问
}
}
]
3. 在路由表中添加路由守卫
路由守卫有三种:
在这里我们使用全局前置守卫进行权限控制,例如:
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
const isAuthenticated = localStorage.getItem('token') // 判断用户是否已经登录
if (requiresAuth && !isAuthenticated) {
next('/login') // 如果需要登录但是用户未登录,则跳转到登录页面
} else {
next() // 如果不需要登录或者用户已经登录,则直接进入路由
}
})
4. 在路由守卫中进行权限判断
在上述代码中,我们使用了localStorage.getItem('token')来判断用户是否已经登录,如果已经登录,则可以访问需要权限的路由,否则跳转到登录页面。在登录成功后,可以将用户的登录状态存储在localStorage中,例如:
localStorage.setItem('token', '123456')
在退出登录时,需要将localStorage中的登录状态清除:
localStorage.removeItem('token')
以上就是在Vue中对路由进行权限控制的步骤。