search
HomeWeb Front-endJS Tutorialvue iview makes dynamic routing

vue iview makes dynamic routing

Jun 08, 2018 am 10:50 AM
vuedynamic routingPermissionsASD

This time I will bring you vue iview to make dynamic routing. What are the precautions for vue iview to make dynamic routing? The following is a practical case, let's take a look.

Achieve the goal

After the client gets the routing and permission data from the server, it refreshes the routing and menu list of the project and controls the permissions.

Project basis

  • ##Basic framework: The template branch project of iview component library official template project iview-admin, this project is of iview-admin Basic framework code. Project address: iview-admin

Implementation logic

Dynamic routing control loading

Generally Said that there are two types of dynamic routing control: one is to store all routing data in local files, and then obtain the user's permission information from the server. When the route jumps, add a permission judgment hook. If the page the user goes to is not Within the permission list, jumping is prohibited. The other is to store only basic routes locally, such as error handling pages, no permission control pages, etc., while permission routes are obtained from the server. The server issues corresponding routing data based on the user's permissions, and the client uses these data for routing. Dynamically generated and added, this article uses the second method.

iview-admin project divides routing into three types:

  • Page routing that is not displayed as a sub-page of the Main component, such as login, 404, 403 and other error pages Routing;

  • is displayed as a sub-page of the Main component but is not displayed in the left menu otherRouter, such as home page routing;

  • is used as the Main component The sub-page is displayed and the routing appRouter is displayed in the left menu;

After getting the routing data, we mainly perform two parts of the operation. The first part is to traverse the data and load it asynchronously using components Method, load the components corresponding to each routing node, and then use

router.addRoutes(routes) to complete the dynamic addition of the route list; the second part is because the page under the iview-admin framework Labels and breadcrumb navigation need to traverse the appRouter to obtain routing information, so we also need to store routing data in vuex for global access.

It is important to note that if the 404 page is a static route, then when you enter the page for the first time, the dynamic route has not been loaded yet. If the routing address cannot be found, it will jump to the 404 error page by default. Experience It's very bad, so the 404 route is not written into the routing rules first, and is loaded together with the dynamic routing.

The main code is implemented as follows:

Data request and routing node generation

//util.js
//生成路由
util.initRouter = function (vm) {
 const constRoutes = [];
 const otherRoutes = [];
 // 404路由需要和动态路由一起注入
 const otherRouter = [{
  path: '/*',
  name: 'error-404',
  meta: {
   title: '404-页面不存在'
  },
  component: 'error-page/404'
 }];
 // 模拟异步请求
 util.ajax('menu.json').then(res => {
  var menuData = res.data;
  util.initRouterNode(constRoutes, menuData);
  util.initRouterNode(otherRoutes, otherRouter);
  // 添加主界面路由
  vm.$store.commit('updateAppRouter', constRoutes.filter(item => item.children.length > 0));
  // 添加全局路由
  vm.$store.commit('updateDefaultRouter', otherRoutes);
  // 刷新界面菜单
  vm.$store.commit('updateMenulist', constRoutes.filter(item => item.children.length > 0));
 });
};
//生成路由节点
util.initRouterNode = function (routers, data) {
 for (var item of data) {
  let menu = Object.assign({}, item);
  menu.component = lazyLoading(menu.component);
  if (item.children && item.children.length > 0) {
   menu.children = [];
   util.initRouterNode(menu.children, item.children);
  }
  //添加权限判断
  meta.permission = menu.permission ? menu.permission : null;
  //添加标题
  meta.title = menu.title ? menu.title : null;
  menu.meta = meta;
 }
};

Dynamic loading of components

//lazyLoading.js
export default (url) =>()=>import(`@/views/${url}.vue`)
Store缓存实现
//app.js
 // 动态添加主界面路由,需要缓存
updateAppRouter (state, routes) {
 state.routers.push(...routes);
 router.addRoutes(routes);
},
// 动态添加全局路由,不需要缓存
updateDefaultRouter (state, routes) {
 router.addRoutes(routes);
},
// 接受前台数组,刷新菜单
updateMenulist (state, routes) {
 state.menuList = routes;
}
Finally in main. Calling in js

//main.js
 mounted () {
 // 调用方法,动态生成路由
 util.initRouter(this);
 }

Permission control

Similar to the dynamic routing implementation method, operation permission control is generally divided into two types. The first is when the page is displayed. Without controlling permissions, all operations, such as buttons, are displayed. Then when the operation is initiated, the permissions are judged. If the user has the permissions for the operation, it passes, otherwise the user is reminded that he does not have permissions. The second is when the page is loaded. , the permissions are judged, and operations without permissions are not displayed. I prefer the second method, which will not mislead the user. I personally think that what the user sees should be operable, otherwise it will be very uncomfortable to click the button and then be prompted that there is no permission.

The source of the idea for this project can be found in the reference blog post. The original blogger’s specific idea is: in the meta field of the routing structure, add a list of user operation permissions, and then register the global command. When the node is rendered for the first time, determine the Whether the page has permissions. If it exists and the parameters passed in are not in the permissions list, delete the node directly.

The main code is implemented as follows:

Add the permission field in the routing data and store the permission list

//menu.json,模拟异步请求数据
[
 {
 "path": "/groupOne",
 "icon": "ios-folder",
 "name": "system_index",
 "title": "groupOne",
 "component": "Main",
 "children": [
  {
  "path": "pageOne",
  "icon": "ios-paper-outline",
  "name": "pageOne",
  "title": "pageOne",
  "component": "group/page1/page1",
  "permission":["del"]
  },
  ...
 ]
 }
]
When traversing to generate routing nodes, store the permission field data in the routing node In the meta attribute

//util.js
//生成路由节点
util.initRouterNode = function (routers, data) {
 for (var item of data) {
  ....
  //添加权限判断
  meta.permission = menu.permission ? menu.permission : null;
  ...
 }
};
define the global command component, read the routing permission attribute value to obtain the permission list, if the permission is not in the permission list, delete the node

//hasPermission.js 
const hasPermission = {
 install (Vue, options) {
  Vue.directive('hasPermission', {
   bind (el, binding, vnode) {
    let permissionList = vnode.context.$route.meta.permission;
    if (permissionList && permissionList.length && !permissionList.includes(binding.value)) {
     el.parentNode.removeChild(el);
    }
   }
  });
 }
};
export default hasPermission;
Permission component usage example:

<template>
 <p>
  </p>
<h1 id="page">page1</h1>
  <button>添加</button>
  <button>修改</button>
  <button>删除</button>
 
</template>

Global registration component

// main.js
import hasPermission from '@/libs/hasPermission.js';
Vue.use(hasPermission);
The advantage of this permission control method is that both management configuration and page processing logic are relatively simple, without a lot of repeated code judgments and For node processing, after referring to and comparing several implementation methods on the Internet, I personally recommend this method.

Page tags and breadcrumbs

In my opinion, page tags and breadcrumbs are the icing on the cake of page-related controls in the system, which improve the convenience of page management. In iview These two components have been implemented in the official admin project. Therefore, in this project, we just transplanted it and implemented the component functions. We did not have an in-depth understanding of it. Those who are interested can study it carefully.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

sortHow to sort son data

Use of vue’s defineProperty attribute

The above is the detailed content of vue iview makes dynamic routing. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment