


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.
Preface
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/#/...
Organization of ideas
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)
Code
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!

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.


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

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

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