SoFunction
Updated on 2025-04-04

Solve the problem of adding dynamic routes for vue2+vue-router and disappearing after refreshing routes

Use vue2 +vuex

Create a new API file under http file

import { getData } from "@/http/";
import store from "@/store/";
import router from "@/router/";
export const getMenu = () => {
  return new Promise((resolve) => {
    var InfoItem = {
      // JobNumber: system_params.UserName ,
      JobNumber: 10086,
      DeviceType: "WEB",
    };
    var newInfoItem = (InfoItem);
    var InfoList = {
      A: 7,
      B: 1,
      C: 1,
      // UserId: system_params.UserName,
      UserId: 10086,
      Data: newInfoItem,
    };
    getData(InfoList).then((res) => {
      if ( === 200 ||  === "") {
        let result = ();
        let routeTree = ();
        ("setUserRouters", routeTree);
        initRoute(routeTree);
        (router);
        resolve(routeTree);
      }
    });
  });
};
function initRoute(menu) {
  if (menu &&  > 0) {
    ((element) => {
      let obj = {
        path: "/" + , // Warehouse management--Warehouse        component: () =>
          import(`@/views/stockInfo/wareHouseManage/${}.vue`),
        meta: {
          title: ,
          path: "/" + ,
        },
      };
      //Add a route      ("index", obj);
      if (element &&  &&  > 0) {
        return initRoute();
      }
      ("router===>", router);
    });
  }
}

In store file

import Vue from "vue";
import Vuex from "vuex";

(Vuex);

// Public statusconst state = {
 
  userRoutes: [],
};

const mutations = {

  setUserRouters(state, payload) {
   
     = payload;
  },
};

export default new ({
  actions,
  mutations,
  state,
  getters,
});

Get backend data

  async mounted() {
    // Get routing data from the background    const mRoutes = getMenu();
     = await mRoutes;
  },

Solution to disappear after dynamic route refresh

//Global pre-router guard——It is called during initialization, and before each route switch((to, from, next) => {
 
  if (load === 0) {
    load++;
    getMenu();
    
    next({ path:  });
  }
  next();
  
});

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.