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?
- How to control permissions in Vue?
- Example demonstration
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.
- Routing level control
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.
- Component level control
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 id="Hello-user-name">Hello, {{ user.name }}</h1> <h2 id="Your-role-is-user-role">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!

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.