Home >Web Front-end >JS Tutorial >Implementation of Vue dynamic routing (pass routing in the background, get it in the front end and generate the sidebar)
This article mainly introduces the implementation of Vue dynamic routing (routing is passed in the background, and the front-end gets and generates the sidebar). It has a certain reference value. Now I share it with you. Friends in need can refer to it
Hell is empty, senior brother is creating on earth. Although it is earthy, it can heal wounds.
The vue project implements dynamic routing in two ways:
1. Write the route on the front end and log in When the route is dynamically displayed based on the user's role permissions, (front-end control routing)
For details, please refer to the project step-by-step of 花Underwear Boss... I looked at this project at the time It took me a long time to understand some logic.
Because the dynamic routing of the master has many layers of judgments, and is interspersed with various vuex, it almost confused me as a novice. It inspired me a lot, and this article is also , provided me with a lot of logic
2. The routing table corresponding to the permissions of the current user is transmitted from the background, and the front-end gets the post-processing (back-end processing routing) through the adjustment interface
These two methods Each has its own advantages and the effect can be achieved. Our company implements it through the second method. The reason is that the company project has a special user center with very complicated logic. It is difficult to return the front-end user permissions and worry about routing. The front-end
is not safe (the above words are said by the company's backend classmates), well, with the attitude of giving everyone a try and exercising their abilities,
we have adopted the second method.
Today we will talk about the idea of using background transfer routing table to realize dynamic routing. Because some of the company's projects use vuex, I have sorted out the routing part separately from vuex so that everyone can There is an inspiration, not an absolute solution, just an idea
github:https://github.com/Mrblackant...
View online: http: //an888.net/antRouter/#/...
The codes corresponding to the following four steps are discussed below, and It is the corresponding
1. The backend students returned a routing table in json format. I used easymock to create a section: dynamic routing table, you can refer to it;
2. Because the backend students returned all String format, but what the front end needs here is a component object. Write a method to traverse it and convert the string into a component object;
3. Use vue-router's beforeEach, addRoutes, localStorage to cooperate with the above two steps to achieve the effect;
4. The left menu bar displays the converted route list;
The general steps: intercept the route->Get the route in the background-> Save the route to localStorage (the user will only fetch it once from the background once when he logs in, and the rest will be fetched from the local, so the route will not be updated until the user logs out and logs in)
1. Routing table
Each route uses the component Layout. This component is the overall page layout: left menu column, right page, so under children The first-level route is your own developed page. The meta contains the name of the route and the icon corresponding to the route;
Because there may be multi-level menus, there will be children nested under children;
The route is in array format
"data": { "router": [ { "path": "", "component": "Layout", "redirect": "dashboard", "children": [ { "path": "dashboard", "component": "dashboard/index", "meta": { "title": "首页", "icon": "dashboard" } } ] }, { "path": "/example", "component": "Layout", "redirect": "/example/table", "name": "Example", "meta": { "title": "案例", "icon": "example" }, "children": [ { "path": "table", "name": "Table", "component": "table/index", "meta": { "title": "表格", "icon": "table" } }, { "path": "tree", "name": "Tree", "component": "tree/index", "meta": { "title": "树形菜单", "icon": "tree" } } ] }, { "path": "/form", "component": "Layout", "children": [ { "path": "index", "name": "Form", "component": "form/index", "meta": { "title": "表单", "icon": "form" } } ] }, { "path": "*", "redirect": "/404", "hidden": true } ] }
2. Convert the "component": "Layout" returned by the backend into the "component": Layout component object
Because of the emergence of multi-level routing, it is necessary to write a traversal recursive method to ensure that each component is converted into an object.
Because the background returns a string, the process of loading components must be encapsulated into a method (refer to the solution of 花Underwear Master here), use this method in traversal; for details, check the _import_development.js and _import_production.js files under the router folder in the project
Layout The directory I put in is different from the directory of other files, so I handle it separately in the traversal. You can adjust it yourself
const _import = require('./router/_import_' + process.env.NODE_ENV)//获取组件的方法 import Layout from '@/views/layout' //Layout 是架构组件,不在后台返回,在文件里单独引入 function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串,转换为组件对象 const accessedRouters = asyncRouterMap.filter(route => { if (route.component) { **加粗文字** if (route.component === 'Layout') {//Layout组件特殊处理 route.component = Layout } else { route.component = _import(route.component) } } if (route.children && route.children.length) { route.children = filterAsyncRouter(route.children) } return true }) return accessedRouters }
3. Use beforeEach, addRoutes, and localStorage to cooperate Implement
beforeEach route interception and enter the judgment. If it is found that there is no routing data locally, use the axios background to fetch it once. After fetching, use localStorage to store it and use addRoutes to dynamically add routes.
ps: beforeEach is good or bad. If you take one careful step, you will enter its infinite loop. The browser will crash. You have to make a judgment at the beginning. Once you get the route, you can directly next(), 嘤嘤嘤
global.antRouter is used to pass data to the left menu component for rendering
import axios from 'axios' var getRouter //用来获取后台拿到的路由 router.beforeEach((to, from, next) => { if (!getRouter) {//不加这个判断,路由会陷入死循环 if (!getObjArr('router')) { axios.get('https://www.easy-mock.com/mock/5a5da330d9b48c260cb42ca8/example/antrouter').then(res => { getRouter = res.data.data.router//后台拿到路由 saveObjArr('router', getRouter) //存储路由到localStorage routerGo(to, next)//执行路由跳转方法 }) } else {//从localStorage拿到了路由 getRouter = getObjArr('router')//拿到路由 routerGo(to, next) } } else { next() } }) function routerGo(to, next) { getRouter = filterAsyncRouter(getRouter) //过滤路由 router.addRoutes(getRouter) //动态添加路由 global.antRouter = getRouter //将路由数据传递给全局变量,做侧边栏菜单渲染工作 next({ ...to, replace: true }) } function saveObjArr(name, data) { //localStorage 存储数组对象的方法 localStorage.setItem(name, JSON.stringify(data)) } function getObjArr(name) { //localStorage 获取数组对象的方法 return JSON.parse(window.localStorage.getItem(name)); }
4. Get the traversed route and render the left menu
The third part above will assign a value to global.antRouter, which is a global variable (can be replaced by vuex). Get the route from the menu and render it. Here is another reference to 花Underwear Master For the layout part, I won’t post the code here.
I have little talent and knowledge. I hope everyone can correct me, especially for the routing interception part. There should be many areas for optimization. Corrections are welcome.
The above is the summary of this article. All content, I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
The above is the detailed content of Implementation of Vue dynamic routing (pass routing in the background, get it in the front end and generate the sidebar). For more information, please follow other related articles on the PHP Chinese website!