【问题标题】:Load dynamic Vue routes from json file从 json 文件加载动态 Vue 路由
【发布时间】:2021-01-25 14:40:15
【问题描述】:

上下文:

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

我遇到的问题是在 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",

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex vue-router


    【解决方案1】:

    您正在寻找 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,
            }]
          );
        }
      },
    
    

    【讨论】:

    • 我明天第一件事会调查它(已经度过了一个令人沮丧的夜晚)。我还没有选择 addRoutes 的原因是我认为当用户直接进入该路由时它可能会不起作用。在 created() 生命周期挂钩期间设置时,它是否已经可供该用户使用?
    • 但是路由器“按顺序”评估路由,因此他的后备路由将优先于新路由。除非他用完全空的路由创建路由器。这甚至可能吗?我不知道。第一次下载数据并在此之后创建路由器(和主 Vue 实例)似乎更容易、更清晰......
    • 再次感谢 Yuri,我决定采用 Michal 的回答,因为我预见到使用 addRoutes 可能会出现一些可能的新问题。 Michal 在这里也指出了其中之一。
    • @MichalLevý 感谢您提及后备路线。那是我的问题。 404PageNotFound 页面正在捕获我在创建路由器后添加的路由。我想我会按照你上面的建议。谢谢!
    【解决方案2】:

    我的首选方法是先下载您的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
      });
    })
    

    【讨论】:

    • 谢谢米哈尔!你的建议就像一个魅力!
    • 很高兴它有帮助!
    猜你喜欢
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2018-10-11
    • 2019-06-16
    • 2020-07-05
    • 2020-09-22
    相关资源
    最近更新 更多