从 json 文件加载动态 Vue 路由

Load dynamic Vue routes from json file

上下文:

我正在构建一个 Vue SPA,在构建应用程序期间,我将大部分内容设置在 json 文件中(可以根据环境变量提供不同的内容)。 我需要用 json 文件中的一些内容设置我的 vue 路由器!

我遇到的问题是在 json 内容可用之前已经设置了路由。我已经阅读了许多相关的解决方案,但无法解决任何问题...


代码:

完全剥离我的代码版本以了解我当前的设置:

我的主应用文件app.js:

Vue.use(VueRouter);

new Vue({
  el: '#app',
  store,
  router,
  methods: {
    async storeStaticContent() {
      // This is where I fetch the content and write it away in the store.
      const response = await fetch(`/static/content.json`);
      const json = await response.json();
      this.$store.commit(MUTATIONS.SET_CONTENT, json);
    },
  },
  created() {
    this.storeStaticContent();
  },
});


我的路由器设置 router.js:

export const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      // The route I need to populate with a string that I write away to the store in my app.js
      {
        path: `/${store.getters.mainEntity}`,
        name: store.getters.mainEntity,
        component: EntityPage,
      },
      {
        path: '/*',
        name: 'not found',
        component: NotFound,
      },
    }
  ],
  base: '/',
  fallback: true,
});

我使用的版本来自 package.json 的两行:

"vue": "^2.6.10",
"vue-router": "^3.1.3",

您正在寻找 addRoutes 方法:

router.addRoutes - Vue Router API

如果您的商店一切正常,应该这样做:

  methods: {
    async storeStaticContent() {
      // This is where I fetch the content and write it away in the store.
      const response = await fetch(`/static/content.json`);
      const json = await response.json();
      this.$store.commit(MUTATIONS.SET_CONTENT, json);
      this.addRoute();
    },
    addRoute: function() {
      this.$router.addRoutes(
        [{
          path: `/${store.getters.mainEntity}`,
          name: store.getters.mainEntity,
          component: EntityPage,
        }]
      );
    }
  },

我的首选方法是先下载 JSON,然后再创建一个路由器,然后 然后 您可以创建主 Vue 实例,将路由器实例传入...

注意:为了简单起见,我省略了 Vuex 的东西...

router.js

export async createRouter() {
    const response = await fetch(`/static/content.json`)
    const json = await response.json();
    const routes = ...generate routes here from the json object
    return new VueRouter({
      routes,
      // other options
    })
}

main.js

import createRouter from `router`

Vue.use(VueRouter);

createRouter().then((router) => {
  new Vue({
    el: '#app',
    store,
    router
  });
})