With the continuous development of front-end technology, more and more front-end frameworks are used in web applications, and one of the most outstanding ones is Vue. Vue is an easy-to-understand and easy-to-use framework that is widely used in the development of web applications. In most web applications, permission control is a crucial part. How to control permissions in Vue has become a very critical issue.
This article will introduce how to perform permission control in Vue, including:
What is permission control?
Permission control is a very important concept, especially important in web applications. Simply put, permission control is to divide users into different categories and assign corresponding user permissions to each category. This way, users can only access content they allow. Permission control can improve the security and stability of applications and make data more secure and reliable.
How to control permissions in Vue?
There are usually two ways to control permissions in Vue: the first is to control at the routing level, and the second is to control at the component level. These two methods will be introduced one by one below.
Control at the routing level. User permissions can be set in the routing metadata meta, and then verified in the routing guard function. If the current user's permissions meet the requirements of this route, the policy proceeds, otherwise it navigates to a different page.
The following is an example of routing:
// 定义路由 const routes = [ { path: '/home', // 路径 name: 'home', // 路由名称 component: Home, // 路由对应的组件 meta: { requireAuth: true, // 需要用户权限 roles: ['admin', 'guest'] // 受访问限制的角色 } }, { path: '/login', // 路径 name: 'login', // 路由名称 component: Login // 路由对应的组件 } ]; // 创建路由实例 const router = new VueRouter({ routes // (缩写)相当于 routes: routes }); // 添加路由前置守卫 router.beforeEach((to, from, next) => { // 判断该路由是否需要登录权限 if (to.meta.requireAuth) { // 如果需要,则校验用户是否已经登录 if (Vue.auth.loggedIn()) { // 判断当前用户是否有访问该路由的权限 if (to.meta.roles.indexOf(Vue.auth.getUserRole()) !== -1) { next() // 用户有访问权限,直接进入页面 } else { next('/denied') // 跳转到其他页面 } } else { // 如果用户未登录,则跳转到登录页面 next('/login') } } else { next() // 如果不需要登录权限,直接进入页面 } });
In the above code, the two attributes requireAuth and roles are set in the metadata meta of the route. requireAuth indicates that the route requires the user to log in before accessing it. roles represents restricted access roles. User permissions can be verified in the beforeEach route guard function. If the user has permission to access the route, enter the page, otherwise jump to other pages. In this way, permission control can be performed at the routing level.
Control at the component level, you can use Vue instructions to control the display and hiding of components. For example, you can set a permission attribute for each component, and then determine in the instruction whether the current user has permission to access the component. If so, display the component, otherwise hide the component.
The following is an example of a component:
<template> <div v-if="allow"> This is a component that requires authentication. </div> <div v-else> You are not authorized to view this component. </div> </template> <script> export default { data() { return { allow: false }; }, mounted() { // 获取当前用户的权限,并根据权限设置组件的显示和隐藏 if (Vue.auth.getCurrentUserRole() === "admin") { this.allow = true; } } }; </script>
In the above code, use the v-if directive to determine whether the current user has permission to access the component, and set the display and display of the component based on the permissions. hide. In this way, permissions can be controlled at the component level.
Example Demonstration
The following is an example demonstration that demonstrates how to perform permission control in Vue.
Suppose you have a web application that contains two pages: a homepage that requires the user to log in to access, and a login page. Control at the routing level, the code is as follows:
const routes = [ { path: "/home", name: "home", component: Home, meta: { requireAuth: true, roles: ["admin", "guest"] } }, { path: "/login", name: "login", component: Login } ]; const router = new VueRouter({ routes }); router.beforeEach((to, from, next) => { if (to.meta.requireAuth) { if (Vue.auth.loggedIn()) { if (to.meta.roles.indexOf(Vue.auth.getUserRole()) !== -1) { next(); } else { next("/denied"); } } else { next("/login"); } } else { next(); } });
In the above code, two routes are defined: home and login, where the home route requires the user to log in to access, while the login route does not require login. After successful login, the user information is saved in the browser's local storage and the vue-auth-plugin plug-in is used to manage the user's status.
Vue.use(VueAuth, { auth: { login(req) { const username = req.body.username; const password = req.body.password; return axios.post("/api/login", {username, password}).then(res => { const data = res.data; localStorage.setItem("user", JSON.stringify(data.user)); this.user.authenticated = true; return true; }); }, logout() { localStorage.removeItem("user"); this.user.authenticated = false; return Promise.resolve(); } }, http: axios, tokenType: "Bearer", tokenName: "Authorization", storageType: "localStorage", user: { roles: JSON.parse(localStorage.getItem("user")).roles } });
In the above code, axios is used to send a login request. After success, the user information is saved in the browser's local storage, and the vue-auth-plugin plug-in is used to manage the user's status. You can use the Vue.auth.loggedIn() method to check whether the user is logged in. If true is returned, it means the user is logged in.
Display user information and logout button on the home page, the code is as follows:
<template> <div> <h1>Hello, {{ user.name }}</h1> <h2>Your role is {{ user.role }}</h2> <button @click="logout">Logout</button> </div> </template> <script> export default { name: "Home", data() { return { user: JSON.parse(localStorage.getItem("user")) }; }, methods: { logout() { Vue.auth.logout().then(() => { this.$router.push("/login"); }); } } }; </script>
In the above code, use the localStorage.getItem() method to obtain the user saved in the local storage information, and then display user information and a logout button. Use the Vue.auth.logout() method to log out and jump to the login page after success.
Summary
Vue is a very powerful web front-end framework. When dealing with permission control, it can be controlled at the routing level and component level, and you can choose the appropriate method according to the actual situation. In practical applications, there are still some details that need to be paid attention to, such as user information management, cross-domain access, etc. But as long as you master the basic permission control principles, you can easily implement permission control in Vue.
The above is the detailed content of How to control permissions in Vue?. For more information, please follow other related articles on the PHP Chinese website!