解決vue2+vue-router動態(tài)路由添加及路由刷新后消失問題
更新時間:2024年08月16日 10:25:57 作者:白臻
這篇文章主要介紹了解決vue2+vue-router動態(tài)路由添加及路由刷新后消失問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
使用的是vue2 +vuex
在http文件下新建api文件 menu.js文件
import { getData } from "@/http/api.js"; import store from "@/store/index.js"; import router from "@/router/index.js"; export const getMenu = () => { return new Promise((resolve) => { var InfoItem = { // JobNumber: system_params.UserName , JobNumber: 10086, DeviceType: "WEB", }; var newInfoItem = JSON.stringify(InfoItem); var InfoList = { A: 7, B: 1, C: 1, // UserId: system_params.UserName, UserId: 10086, Data: newInfoItem, }; getData(InfoList).then((res) => { if (res.Code === 200 || res.Msg === "") { let result = JSON.parse(res.Data); let routeTree = JSON.parse(result.List); store.commit("setUserRouters", routeTree); initRoute(routeTree); console.log(router); resolve(routeTree); } }); }); }; function initRoute(menu) { if (menu && menu.length > 0) { menu.forEach((element) => { let obj = { path: "/" + element.menuUrl, // 倉庫管理--倉庫 component: () => import(`@/views/stockInfo/wareHouseManage/${element.menuUrl}.vue`), meta: { title: element.menuName, path: "/" + element.menuUrl, }, }; //添加路由 router.addRoute("index", obj); if (element && element.Children && element.Children.length > 0) { return initRoute(element.Children); } console.log("router===>", router); }); } }
在store文件里
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); // 公共狀態(tài) const state = { userRoutes: [], }; const mutations = { setUserRouters(state, payload) { state.userRoutes = payload; }, }; export default new Vuex.Store({ actions, mutations, state, getters, });
獲取后臺數(shù)據(jù)
async mounted() { // 從后臺獲取路由數(shù)據(jù) const mRoutes = getMenu(); this.menus = await mRoutes; },
動態(tài)路由刷新后消失解決辦法
//全局前置路由守衛(wèi)————初始化的時候被調(diào)用、每次路由切換之前被調(diào)用 router.beforeEach((to, from, next) => { if (load === 0) { load++; getMenu(); next({ path: to.fullPath }); } next(); });
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- vue實現(xiàn)動態(tài)路由的詳細(xì)代碼示例
- Vue實現(xiàn)動態(tài)路由的示例詳解
- Vue?Router動態(tài)路由實現(xiàn)實現(xiàn)更靈活的頁面交互
- vue3實現(xiàn)動態(tài)路由及菜單
- vue3動態(tài)路由+菜單欄的實現(xiàn)示例
- 在Vue3中實現(xiàn)動態(tài)路由的示例代碼
- Vue3動態(tài)路由(響應(yīng)式帶參數(shù)的路由)變更頁面不刷新的問題解決辦法
- Vue3+Vue Router實現(xiàn)動態(tài)路由導(dǎo)航的示例代碼
- 前端單獨實現(xiàn)vue動態(tài)路由的示例代碼
相關(guān)文章
前端低代碼form-generator實現(xiàn)及新增自定義組件詳解
這篇文章主要給大家介紹了關(guān)于前端低代碼form-generator實現(xiàn)及新增自定義組件的相關(guān)資料,form-generator是一個開源的表單生成器,可以幫助我們快速構(gòu)建各種表單頁面,需要的朋友可以參考下2023-11-11Vue-router不允許導(dǎo)航到當(dāng)前位置(/path)錯誤原因以及修復(fù)方式
本文主要介紹了Vue-router不允許導(dǎo)航到當(dāng)前位置(/path)錯誤原因以及修復(fù)方式,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09