vue iview makes dynamic routing
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;
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.
//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; }
//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"] }, ... ] } ]
//util.js //生成路由节点 util.initRouterNode = function (routers, data) { for (var item of data) { .... //添加权限判断 meta.permission = menu.permission ? menu.permission : null; ... } };
//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;
<template> <p> <h1>page1</h1> <Button v-hasPermission="'add'">添加</Button> <Button v-hasPermission="'edit'">修改</Button> <Button v-hasPermission="'del'">删除</Button> </p> </template>
Global registration component
// main.js import hasPermission from '@/libs/hasPermission.js'; Vue.use(hasPermission);
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:
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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() => { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.
