Home >Web Front-end >Vue.js >How to implement permission control and routing guards in Vue?
How to implement permission control and routing guards in Vue?
As an excellent front-end framework, Vue provides many convenient functions to help us build applications. Among them, routing and permission control are an indispensable part. In development, we often need to restrict pages to only allow specific users or permissions to be visible. At this time, Vue's routing guard and permission control functions come in handy.
1. Permission Control
Vue implements permission control through the meta attribute of routing configuration. You can do this:
You can add permission control to the meta attribute of the route to determine whether you have permission to access the page.
{ path: '/dashboard', name: 'Dashboard', component: Dashboard, meta: { requiresAuth: true } }
Vue uses routing guards to protect pages from illegal access. You can add the hook function beforeEnter in the route to determine whether you have access permission before entering the page.
const router = new VueRouter({ routes: [ { path: '/dashboard', name: 'Dashboard', component: Dashboard, meta: { requiresAuth: true }, beforeEnter: (to, from, next) => { if (!store.getters.isLoggedIn) { next('/login'); } else { next(); } } } ] })
Note that store.getters.isLoggedIn is a getter function defined in Vuex, which is responsible for determining whether the user has logged in.
2. Route guard
Use Vue's route guard to intercept the user when the route jumps and process the user's access.
Global route guard will be triggered when any route jumps, and can be used to process global data such as login status and user information.
router.beforeEach((to, from, next) => { // 判断用户是否登录 if (to.matched.some(record => record.meta.requiresAuth)) { if (!store.getters.isLoggedIn) { next({ path: '/login', query: { redirect: to.fullPath } }) } else { next() } } else { next() } })
Route exclusive guard is set in the current routing configuration and can intercept certain routes individually.
{ path: '/dashboard', name: 'Dashboard', component: Dashboard, beforeEnter: (to, from, next) => { // 判断用户权限 if (store.getters.getPermission === ‘admin’) { next() } else { next({ path: '/login', query: { redirect: to.fullPath } }) } } }
Determine whether the user permissions are sufficient in the beforeEnter hook function. If not, jump to the login page.
Summary
Implementing permission control and routing guards in Vue is a very convenient process. By setting the route's meta attribute and using route guards, we can control access to pages based on the user's login status and permissions. This not only ensures the security of the application, but also improves the user experience.
The above is the detailed content of How to implement permission control and routing guards in Vue?. For more information, please follow other related articles on the PHP Chinese website!