2. Detailed explanationThe overall idea is: login > get menu based on user information after success > generate routing information based on menu 2.1. Add asyncRoutes routing Add asyncRoutes array in the vue-router path export const asyncRoutes = [ { path: '*', redirect: '/404', hidden: true } ] The difference between constantRoutes and asyncRoutes constantRoutes: Routes that do not require dynamic authority determination, such as login pages, 404 pages, and other general pages. asyncRoutes: requires dynamic authority judgment and dynamically added pages through addRoutes 2.2. Create a new permission.js file Create a new permission.js file under the vuex path import { asyncRoutes, constantRoutes } from '@/router' import { fetchUserMenuList } from '@/api/user' import Layout from '@/layout' /** * Static route lazy loading * @param view format must start with xxx/xxx without slash * @returns */ export const loadView = (view) => { return (resolve) => require([`@/views/${view}.vue`], resolve) } /** * Assemble the menu data queried from the backend into routing format data* @param routes * @param data menu data returned by the backend */ export function generaMenu(routes, data) { data.forEach(item => { const menu = { path: item.url, component: item.component === '#' ? Layout : loadView(item.component), hidden: item.status === 0, // hidden redirect with status 0: item.redirect, children: [], name: item.code, meta: item.meta } if (item.children) { generaMenu(menu.children, item.children) } routes.push(menu) }) return routes } const state = { routes: [], addRoutes: [] } const mutations = { SET_ROUTES: (state, routes) => { state.addRoutes = routes // Concatenate static routes and dynamic routes state.routes = constantRoutes.concat(routes) } } const actions = { generateRoutes({ commit }, token) { return new Promise(resolve => { // Get the user menu from the backend through token and add it to the global state fetchUserMenuList(token).then(res => { const menuData = Object.assign([], res.data) const tempAsyncRoutes = Object.assign([], asyncRoutes) const accessedRoutes = generaMenu(tempAsyncRoutes, menuData) commit('SET_ROUTES', accessedRoutes) resolve(accessedRoutes) }).catch(error => { console.log(error) }) }) } } export default { namespaced: true, state, mutations, actions } 2.3. Register the permission module in vuex If you are using vue-element-admin, please skip this step because it automatically registers all modules under import Vue from 'vue' import Vuex from 'vuex' import getters from './getters' Vue.use(Vuex) // https://webpack.js.org/guides/dependency-management/#requirecontext const modulesFiles = require.context('./modules', true, /\.js$/) // you do not need `import app from './modules/app'` // it will auto require all vuex modules from modules file const modules = modulesFiles.keys().reduce((modules, modulePath) => { // set './app.js' => 'app' const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1') const value = modulesFiles(modulePath) modules[moduleName] = value.default return modules }, {}) const store = new Vuex.Store({ modules, getters }) export default store 2.4. Add routing status in getters Add menuRoutes state in vuex path menusRoutes: state => state.permission.routes 2.5. Modify the source of menu generation data Modify the routes data source in the path routes() { // return this.$router.options.routes return this.$store.getters.menusRoutes }, At this point, the logic from getting menu data from the backend to page display has been completed. Now let's start calling it after logging in. 2.6. Get the menu after logging in In the login method of the vuex path // Get the menu. When calling actions in other files, you must add { root: true } dispatch('permission/generateRoutes', data, { root: true }).then((accessRoutes) => { router.addRoutes(accessRoutes) }) 2.7. Solve the problem of page blank after refreshThe above content can already realize the function of displaying the left menu after logging in, but you will find that the page will become blank every time you refresh the page. This is because when the page is refreshed, the vue instance will be reloaded, and the data in the vuex store will be reassigned, causing the routing information in vuex to be cleared. Add the code for retrieving routes in const accessRoutes = await store.dispatch('permission/generateRoutes', store.getters.token) router.addRoutes(accessRoutes) next({ ...to, replace: true }) 3. SummarySo far, the dynamic acquisition of menu content based on user information has been completed. This is the end of this article about using the vue-element-admin framework to dynamically obtain menus from the backend. For more relevant vue-element-admin dynamic menu acquisition content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Detailed explanation of mysql permissions and indexes
>>: Example of how to install kong gateway in docker
1. For comparison of date size, the date format p...
Today we will introduce how to publish the local ...
Table of contents 1. Master-slave synchronization...
Scenario: The interaction methods between parent ...
introduction: Slider drag verification is now use...
grammar: background-image: conic-gradient(from an...
Easy installation of opencv2: conda install --cha...
1. Use absolute positioning and margin The princi...
Preface I watched web.dev's 2020 three-day li...
MySQL's index types include normal index, uni...
Table of contents Preface The role of deconstruct...
Preface: In MySQL, the CONCAT() function is used ...
This article mainly introduces the solution to th...
The role of the a tag pseudo-class: ":link&qu...
A style sheet describes how a document should be ...