Vue路由权限可以通过以下步骤进行配置:
-
首先,在Vue项目中安装并引入Vue Router插件:
npm install vue-router --save
,并在Vue实例中使用该插件。 -
在Vue路由配置文件中,可以为每个路由设置一个
meta
对象,用于存储该路由的权限信息。例如,可以添加一个requiresAuth
属性,表示该路由需要登录才能访问:const routes = [ { path: '/home', component: Home, meta: { requiresAuth: true } }, // ... ]
-
在Vue实例中添加全局导航守卫,在路由跳转时判断用户是否已经登录,如果未登录并且该路由需要登录权限,则跳转到登录页面:
router.beforeEach((to, from, next) => { const isAuthenticated = localStorage.getItem('user') if (to.matched.some(record => record.meta.requiresAuth)) { if (!isAuthenticated) { next({ path: '/login', query: { redirect: to.fullPath } }) } else { next() } } else { next() } })
在上述代码中,我们通过
localStorage
判断用户是否已登录,如果未登录则将用户重定向到登录页面,并在登录后跳转回原来的路由。 -
最后,在组件中添加访问该路由需要的权限信息,例如:
<template> <div> <h2 v-if="$route.meta.requiresAuth">需要登录才能访问该页面</h2> </div> </template>
通过以上步骤,我们就可以根据路由的权限信息,控制用户的访问权限。