How to implement permission management function using vue
This article mainly introduces the permission management of the website front-end based on vue (the practice of separation of front-end and back-end). Now I share it with you and give you a reference.
As a popular language nowadays, Javascript is widely used and can be seen everywhere from front-end to back-end. This technology is now also widely used within our projects to develop CMS systems and other data analysis systems. The front-end page, for which I am very interested and uses it as an extended content of the hat card for after-school learning.
There are many Javascript frameworks, but the basic principles are roughly the same, so we chose vue.js developed by domestic people to make a preliminary attempt. It has been more than a week since I learned vue.js. Speaking of the main uses of vue, there are nothing more than Declarative Rendering, Component System, Client-side Routing, Vue-resource, Axios, and Vuex depending on the size of the project. Learn vue It's a small matter, but the main thing is to change your thinking. The component-based web development that separates the front and back ends is what you really want to practice.
It just so happens that my personal website CodeSheep needs to develop backend management recently, so I just used vue to implement it. When it comes to backend management, the unavoidable issue is permission management. Since we want to practice the idea of separation of front-end and back-end, all web front-end things managed by the backend should be completed independently by the front-end. This includes the very important front-end control of related things based on permissions. What we want to achieve is: different permissions correspond to different routes. At the same time, the sidebar of the page should also asynchronously generate the corresponding menu according to different permissions. To put it bluntly, users with different permissions see it during background management. The interface menu is different, so there is a set of processes for login and permission verification.
Specific implementation
1. Click the "Login" button to trigger the login event
this.$store.dispatch('LoginByEmail', this.loginForm).then(() => { this.$router.push({ path: '/' }); //登录成功之后重定向到首页 }).catch(err => { this.$message.error(err); //登录失败提示错误 });
The asynchronously triggered actions LoginByEmail processing content is as follows:
LoginByEmail ({ commit }, userInfo) { const email = userInfo.email.trim() return new Promise((resolve, reject) => { loginByEmail(email, userInfo.password).then(response => { const data = response.data setToken(response.data.token) commit('SET_TOKEN', data.token) resolve() }).catch(error => { reject(error) }) }) }
It is easy to see that what you want to do is to put the token obtained from the server (which uniquely identifies the user's identity) into the browser's local Cookie
2. Intercept in the global hook router.beforeEach Routing
This step is the core. The specific processing flow is as follows:
Routing interception processing flow
The specific code is as follows:
router.beforeEach((to, from, next) => { if (getToken()) { // 判断是否取到token if (to.path === '/login') { next({ path: '/' }) } else { if (store.getters.roles.length === 0) { // 判断当前用户是否已获取完user_info信息 store.dispatch('GetInfo').then(res => { // 获取user_info const roles = res.data.role store.dispatch('GenerateRoutes', { roles }).then(() => { // 生成可访问的路由表 router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表 next({ ...to }) // 放行路由 }) }).catch(() => { store.dispatch('FedLogOut').then(() => { next({ path: '/login' }) }) }) } else { next() // 放行该路由 } } } else { if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单里的路径,继续让其访问 next() } else { // 其他不在白名单里的路径全部让其重定向到登录页面! next('/login') alert('not in white list, now go to the login page') } } })
Explain some important steps in the flow chart:
Judge whether the front-end has obtained the token: getToken()
The operation is very simple, mainly from the Cookie Obtain and see if the token has been obtained:
export function getToken () { return Cookies.get(TokenKey) }
vuex asynchronous operation store.dispatch('GetInfo'): Obtain user information
GetInfo ({ commit, state }) { return new Promise((resolve, reject) => { getInfo(state.token).then(response => { const data = response.data console.log(data) commit('SET_ROLES', data.role) commit('SET_NAME', data.name) resolve(response) }).catch(error => { reject(error) }) }) }
The operation is also very simple, using a get restful api Get the user's role and name from the server
vuex asynchronous operation store.dispatch('GenerateRoutes', {roles}): generate different front-end routes based on different roles
GenerateRoutes ({ commit }, data) { return new Promise(resolve => { const { roles } = data let accessedRouters if (roles.indexOf('admin') >= 0) { accessedRouters = asyncRouter } else { accessedRouters = filterAsyncRouter(asyncRouter, roles) } commit('SET_ROUTERS', accessedRouters) resolve() }) }
From the code It can be seen that I only distinguish between the administrator role admin and other ordinary users (that is, non-Aadmin two permissions)
I will try more in this series of practices and will write them one by one. , I am also a beginner, and the journey is long and searching. . .
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement communication in vue2.0?
Angular 2 What are the methods of style binding
What are the differences between on and click in jquery?
What are the differences between on and click in jquery?
Taobao-like JSsearch (detailed tutorial)
The above is the detailed content of How to implement permission management function using vue. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

InternationalizationandlocalizationinVueappsareprimarilyhandledusingtheVueI18nplugin.1.Installvue-i18nvianpmoryarn.2.CreatelocaleJSONfiles(e.g.,en.json,es.json)fortranslationmessages.3.Setupthei18ninstanceinmain.jswithlocaleconfigurationandmessagefil

Server-siderendering(SSR)inVueimprovesperformanceandSEObygeneratingHTMLontheserver.1.TheserverrunsVueappcodeandgeneratesHTMLbasedonthecurrentroute.2.ThatHTMLissenttothebrowserimmediately.3.Vuehydratesthepage,attachingeventlistenerstomakeitinteractive

ToaddtransitionsandanimationsinVue,usebuilt-incomponentslikeand,applyCSSclasses,leveragetransitionhooksforcontrol,andoptimizeperformance.1.WrapelementswithandapplyCSStransitionclasseslikev-enter-activeforbasicfadeorslideeffects.2.Useforanimatingdynam

Building a Vue component library requires designing the structure around the business scenario and following the complete process of development, testing and release. 1. The structural design should be classified according to functional modules, including basic components, layout components and business components; 2. Use SCSS or CSS variables to unify the theme and style; 3. Unify the naming specifications and introduce ESLint and Prettier to ensure the consistent code style; 4. Display the usage of components on the supporting document site; 5. Use Vite and other tools to package as NPM packages and configure rollupOptions; 6. Follow the semver specification to manage versions and changelogs when publishing.

nextTick is used in Vue to execute code after DOM update. When the data changes, Vue will not update the DOM immediately, but will put it in the queue and process it in the next event loop "tick". Therefore, if you need to access or operate the updated DOM, nextTick should be used; common scenarios include: accessing the updated DOM content, collaborating with third-party libraries that rely on the DOM state, and calculating based on the element size; its usage includes calling this.$nextTick as a component method, using it alone after import, and combining async/await; precautions include: avoiding excessive use, in most cases, no manual triggering is required, and a nextTick can capture multiple updates at a time.

1. The first choice for the Laravel MySQL Vue/React combination in the PHP development question and answer community is the first choice for Laravel MySQL Vue/React combination, due to its maturity in the ecosystem and high development efficiency; 2. High performance requires dependence on cache (Redis), database optimization, CDN and asynchronous queues; 3. Security must be done with input filtering, CSRF protection, HTTPS, password encryption and permission control; 4. Money optional advertising, member subscription, rewards, commissions, knowledge payment and other models, the core is to match community tone and user needs.

"Useraccounts" manages user identities, and "Privileges" manages user permissions. Specifically: 1. Useraccounts is used to create and delete users, view username, host, and password status, and modify login credentials or connection restrictions; 2. Privileges is used to assign or revoke database and table-level operation permissions, such as SELECT, INSERT, UPDATE, DELETE, and global permissions such as overloading MySQL server or granting other user permissions. The two are clearly divided and are often used together. For example, first create a user in Useraccounts, and then use Privilege.
