簡體   English   中英

從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",

我更喜歡的方法是先下載你的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
  });
})

您正在尋找 addRoutes 方法:

router.addRoutes - Vue 路由器 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,
        }]
      );
    }
  },

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM