Vue realizes the access management of the website foreground

Source: Internet
Author: User
This article mainly introduces the realization of the site based on Vue access management (front and back end separation practice), small series feel very good, and now share to everyone, but also for everyone to do a reference. Follow the small series together to see it, hope to help everyone.

JavaScript is a popular language for the moment and is widely used, from the front-end to the back-end, and it is now heavily utilized within our projects to develop front-end pages for CMS systems and other data analysis systems. This person is very interested and as a Hat card extension content to study after school.
JavaScript frameworks are lined up, but the fundamentals are roughly the same, so a tentative attempt is made to choose the vue.js developed by the domestic people. Study Vue.js also more than a week time, talking about the main use of Vue, no outside declarative Rendering, Component System, Client-side Routing, Vue-resource, Axios and depending on the size of the project to decide whether to use the Vuex, learning vue Small, the main transformation of thinking, front-end separation of the component-based web development is really want to practice.

Just my personal site Codesheep recently to develop background management, so just use Vue this set to achieve a bit. When it comes to background management, the problem that is not open is the management of authority. Since you want to practice the front-end separation of this idea, so the background management of all Web front-end things should be independent of the front-end, which includes very important by the front-end to the control of the relevant things according to permissions. What we want to do is: Different permissions for different routes, and the page sidebar should also be based on different permissions, to asynchronously generate the corresponding menu, white is the background management when the user of different permissions to see the interface menu is not the same, so there is a set of procedures for login and authorization here.
Specific implementation

1. Click "Login" button to trigger the login event.


this. $store. Dispatch (' Loginbyemail ', this.loginform). then (() = {this. $router. Push ({path: '/'});//redirect to home page after successful login} ). catch (Err = {this. $message. Error (ERR);//Login failed prompt});

The actions of the loginbyemail that are triggered asynchronously are as follows:


Loginbyemail ({commit}, UserInfo) {   Const email = userInfo.email.trim ()   return new Promise ((Resolve, Reject) =&G T {    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's easy to see what you want to do is put the token (uniquely labeled user) from the server to a local cookie in the browser

2. Intercept route in Global Hook Router.beforeeach

This step is the core, the specific processing flow is shown as follows:

Routing interception processing flow

The specific code is as follows:


Router.beforeeach (to, from, next) = {if (GetToken ()) {///To determine whether to take the token  if (To.path = = = '/login ') {   Next {Pat H: '/'}  } else {   if (store.getters.roles.length = = 0) {//Determine if the current user has finished User_info information    store.dispatch (' GetInfo '). Then (res = {//get user_info     Const roles = Res.data.role     store.dispatch (' Generateroutes ', {roles} ). Then (() = {//Generate accessible routing table      Router.addroutes (store.getters.addRouters)//Dynamically add accessible routing table      next ({... to})//release route c9/>})    . catch (() = {     Store.dispatch (' fedlogout '). then (() = {      Next ({path: '/login '})     } )}    )   } else {    next ()//release the Route   }}  } else {  if (Whitelist.indexof (To.path)!==-1) {//sign-in white The path in the list, continue to let it access   next ()  } else {//other not on the whitelist path all redirect it to the login page!   next ('/login ')   alert (' Not at White list, now go to the login page ')}}  )

A few important steps in the flowchart explain:

Determine if the front end is taking token tokens: GetToken ()

The operation is very simple, mainly from the cookie, to see if token has been obtained:


Export function GetToken () {return cookies.get (Tokenkey)}

Vuex Asynchronous Operation Store.dispatch (' GetInfo '): Get user Information


  GetInfo ({commit, state}) {   return new Promise ((resolve, reject) = {    GetInfo (state.token). Then (response =&G T {     Const data = Response.data     console.log (     ' set_roles ', data.role)     commit (' Set_name ', Data.name)     Resolve (response)    }). catch (Error = {     reject (Error)})}   )  }

The operation is also simple, using a Get RESTful API to get the user's role and name from the server

Vuex Asynchronous Operation Store.dispatch (' Generateroutes ', {roles}): Generate different foreground routes based on different roles


  Generateroutes ({commit}, data) {   return new Promise (resolve = {    const {Roles} = data let    accessedrout ERs    if (roles.indexof (' admin ') >= 0) {     accessedrouters = Asyncrouter    } else {     accessedrouters = Filterasyncrouter (asyncrouter, roles)    }    commit (' set_routers ', accessedrouters)    resolve ()   })  }

As can be seen from the code, I have only distinguished between admin roles admin and other ordinary users (that is, non-aadmin two permissions)

The series of practical follow-up will also try more, will be written, I am a beginner, the road is long and quest ...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.