There are several dynamic load routing schemes
- The front end sets its own routing table according to different users.
- Back-end brothers set up routing tables, front-end request interface to get the routing table
The first method is adopted in this paper.
A general idea:
- Setting up different routing tables
- Store part of user registration information in vux
- Different routing tables are added to the current routing table according to the user's different identities when the component is created and when the login request is successful. The first one is to prevent the user from clicking on refresh and causing routing initialization. The second one is to prepare the corresponding routing table immediately after the login is successful.
Note: 404 routing is written in dynamic routing. Otherwise, there may be flash screens and 404 pages loaded for space-time routing.
1. Setting up routing table
//Manager Routing export const ManagerRouter = [ { path: "/index", component: Index, children: [ { path: "/infolist", name: "InfoList", component: InfoList }, { path: "/fundlist", name: "FundLst", component: FundList } ] }, ]; //Public routing const PublicRouter = [ { path: "/index", component: Index, children: [ { path: "", component: Home }, { path: "/home", name: "Home", component: Home } ] }, { path: "/register", name: "Register", component: Register }, { path: "/login", name: "Login", component: Login }, { path: "*", name: "NotFound", component: NotFound } ];
2.vuex saves user information
3. Add the corresponding routing table according to user privileges (first, the APP root component uses this. $router. addRoutes (new Routes))
···Eliminate other code created(){ // Resolve state initialization after refresh if(sessionStorage.eleToken){ //Parsing token const decode = jwt_decode(sessionStorage.eleToken); //Dynamic Rendering Routing if(decode.identity == 'manager'){ this.$router.addRoutes(ManagerRouter); } //Store parsed token in vuex this.$store.dispatch('setAuthenticated',!this.isEmpty(decode)); this.$store.dispatch('setUser',decode); } },
4. Login components add routing tables based on user information
submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { this.$axios.post('/login',this.loginUser) .then(res=>{ // console.log(res); //Storage Token const {token} = res.data; sessionStorage.setItem("eleToken",token); //Parsing token const decode = jwt_decode(token); //Dynamic Rendering Routing if(decode.identity == 'manager'){ this.$router.addRoutes(ManagerRouter); } //Store parsed token in vuex this.$store.dispatch('setAuthenticated',!this.isEmpty(decode)); this.$store.dispatch('setUser',decode); //Jump to Home Page this.$router.push('/index'); }) } }); },
Reference article: vue-router routing privilege control