Configuring dynamic Routing

To configure a dynamic route, perform two steps: 1. Obtain route information from the back-end. 2

  1. Set the static route pages such as login page,404 page, and error page. These static route pages are not obtained from the backend
  2. In the router’s hook function, route.beforeeach (), the dynamic routing information is retrieved and cached in Vuex for later rendering menus
  3. After obtaining the routing information, add the routing information object to the Router by router.addroute ()
  4. Handles a 404 page jump on refresh
// Set the dynamic router. BeforeEach ((to, from, next) => {const token = getToken(); If (to.fullpath! = '/login' &&token) {// Determine the data in Vuex to avoid data loss in page refresh. If there is no data in Vuex, then send the request to get the data if (store. State. Permission. Routes = = 0) {/ / get data by Vuex, and store the data and the routing information added to the router Store. Dispatch ('GenerateRoutes'). Then (res => {path: '*', redirect: '/404'}; Router.addroute (o); router.addroute (o); next({ ... to, replace: true }); // hack to make sure addRoutes is complete}); } else { next(); } } else { next(); }}); / / Vuex -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- const permission = {state: {routes: []}, mutations: {SET_ROUTES: (state, routes) => { state.routes = routes; } }, actions: GenerateRoutes({commit}) {return new Promise(resolve => {// getUserMenus(). Then (res => { // Process the data and add it to the Router setRouter(res.data); Commit ('SET_ROUTES', res.data); commit('SET_ROUTES', res.data); resolve(res); }); }); }}}; Function setRouter(data) {let list = []; Data. forEach(item => {if (item.children) {list = list.concat(item.children); }}); List. ForEach (item => {// handle mate item.meta = {title: item.name}; Item.ponent = getView(item.ponent); // Add router. AddRoute ('level', item); }); Function getView(viewUrl) {return (resolve) => require([' @/components/page/${viewUrl} '], resolve); } export default permission;Copy the code

The 404 page is redirected after the dynamic route is refreshed

After dynamic routes are configured, the page 404 is displayed if you refresh the page

  • Cause: The dynamic route is not added to the route
  • Solution: After adding all the pages, add the generic matching, redirect 404 route configuration

\