Table of Contents
Preface
Organization of ideas
Code
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)

Implementation of Vue dynamic routing (pass routing in the background, get it in the front end and generate the sidebar)

Jul 09, 2018 pm 02:25 PM
element-ui vue-router vue.js

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/#/...
Implementation of Vue dynamic routing (pass routing in the background, get it in the front end and generate the sidebar)

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
      }
    ]
  }
Copy after login

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
}
Copy after login

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));

}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

I encountered the vue-router error 'NavigationDuplicated: Avoided redundant navigation to current location' in my Vue application - how to solve it? I encountered the vue-router error 'NavigationDuplicated: Avoided redundant navigation to current location' in my Vue application - how to solve it? Jun 24, 2023 pm 02:20 PM

The vue-router error "NavigationDuplicated:Avoidedredundantnavigationtocurrentlocation" encountered in the Vue application – how to solve it? Vue.js is becoming more and more popular in front-end application development as a fast and flexible JavaScript framework. VueRouter is a code library of Vue.js used for routing management. However, sometimes

How to use Vue and Element-UI to implement lazy loading of images How to use Vue and Element-UI to implement lazy loading of images Jul 22, 2023 pm 04:05 PM

How to use Vue and Element-UI to implement lazy loading of images Lazy loading (Lazyloading) is a technology that delays loading of images, which can effectively increase page loading speed, save bandwidth and improve user experience. In the Vue project, we can use Element-UI and some plug-ins to implement the image lazy loading function. This article will introduce how to use Vue and Element-UI to implement lazy loading of images, and attach corresponding code examples. 1. Install the necessary dependencies before starting

How to implement calendar and date selection functions using Vue and Element-UI How to implement calendar and date selection functions using Vue and Element-UI Jul 22, 2023 pm 05:30 PM

Introduction to how to use Vue and Element-UI to implement calendar and date selection functions: In front-end development, calendar and date selection functions are one of the very common requirements. Vue and Element-UI are a pair of very powerful development tools. Combining them can easily implement calendar and date selection functions. This article will introduce how to use Vue and Element-UI to create a simple calendar and date selection function, and provide code examples to help readers understand the specific steps and methods of implementation. Preparation: at the beginning

A complete guide to implementing file upload in Vue (axios, element-ui) A complete guide to implementing file upload in Vue (axios, element-ui) Jun 09, 2023 pm 04:12 PM

A complete guide to implementing file upload in Vue (axios, element-ui) In modern web applications, file upload has become a basic function. Whether uploading avatars, pictures, documents or videos, we need a reliable way to upload files from the user's computer to the server. This article will provide you with a detailed guide on how to use Vue, axios and element-ui to implement file upload. What is axiosaxios is a prom based

How to use Vue and Element-UI to implement message notification function How to use Vue and Element-UI to implement message notification function Jul 21, 2023 pm 12:40 PM

How to use Vue and Element-UI to implement message notification functions. With the continuous development of front-end technology, more and more websites and applications need to implement message notification functions in order to display important information to users in a timely manner. In Vue development, this function can be quickly realized by combining the Element-UI framework. This article will introduce in detail how to use Vue and Element-UI to implement the message notification function, and provide relevant code examples. 1. Preparation work is implemented using Vue and Element-UI

How to use Vue and Element-UI to implement multi-level linkage drop-down box function How to use Vue and Element-UI to implement multi-level linkage drop-down box function Jul 20, 2023 pm 11:43 PM

How to use Vue and Element-UI to implement multi-level drop-down box function Introduction: In web development, multi-level linkage drop-down box is a common interaction method. By selecting an option in a drop-down box, the contents of subsequent drop-down boxes can be dynamically changed. This article will introduce how to use Vue and Element-UI to implement this function, and provide code examples. 1. Preparation First, we need to ensure that Vue and Element-UI have been installed. It can be installed via the following command: npmins

How to use Vue and Element-UI to implement data filtering and search functions How to use Vue and Element-UI to implement data filtering and search functions Jul 21, 2023 pm 08:40 PM

How to use Vue and Element-UI to implement data filtering and search functions. In modern web development, data filtering and search functions are very common and important requirements. Vue and Element-UI are currently very popular front-end frameworks. They provide many powerful tools and components that can help us easily implement data filtering and search functions. This article will introduce how to use Vue and Element-UI to implement these functions, and provide detailed code examples. First, we need to prepare a

How to use Vue and Element-UI to implement drag-and-drop sorting function How to use Vue and Element-UI to implement drag-and-drop sorting function Jul 22, 2023 pm 04:12 PM

How to use Vue and Element-UI to implement drag-and-drop sorting function Preface: In web development, drag-and-drop sorting function is a common and practical function. This article will introduce how to use Vue and Element-UI to implement the drag-and-drop sorting function, and demonstrate the implementation process through code examples. 1. Environment setup and installation Node.js Before starting, you need to install Node.js. You can visit https://nodejs.org/ to download and install the version corresponding to the operating system. Install VueCL

See all articles