【问题标题】:How to extract only the routes from vue router to generate sitemap如何仅从 vue 路由器中提取路由以生成站点地图
【发布时间】:2019-05-18 13:53:46
【问题描述】:

我有一个导出我的 VueRouter 实例的文件:

// src/js/router.js

import VueRouter from "vue-router";

export default new VueRouter({
  mode: "history",
  routes: [
    {
      name: "home",
      path: "/",
      component: "./component/Home.vue"
    },
    {
      name: "contact-us",
      path: "/contact-us",
      component: "./component/ContactUs.vue"
    }
  ]
});

尝试

我试图执行这个文件:

// test.js

import router from "./src/js/router.js";

使用节点:

node --experimental-modules test.js

但是我遇到了这个错误:

$ node --experimental-modules test.js (节点:13688) ExperimentalWarning:ESM 模块加载器是实验性的。 C:\xampp\htdocs\extract-routes-from-vue-router\test.js:1 (function (exports, require, module, __filename, __dirname) { import router from > "./src/js/router.js"; ^^^^^^

SyntaxError:意外的标识符 在新脚本 (vm.js:80:7) 在 createScript (vm.js:274:10) 在 Proxy.runInThisContext (vm.js:326:10) 在 Module._compile (internal/modules/cjs/loader.js:664:28) 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10) 在 Module.load (internal/modules/cjs/loader.js:600:32) 在 tryModuleLoad (internal/modules/cjs/loader.js:539:12) 在 Function.Module._load (internal/modules/cjs/loader.js:531:3) 在 createDynamicModule (internal/modules/esm/translators.js:73:15) 在 Object.meta.done (internal/modules/esm/create_dynamic_module.js:42:9)

问题

如何从路由器中仅提取path 密钥?我想根据我的路由器路由生成站点地图。

【问题讨论】:

    标签: javascript node.js vue.js vue-router sitemap


    【解决方案1】:

    site 上有一个示例,可以将所有路由作为链接数组获取:

    const router = new Router({ /* Your Router config go here */ });
    
    function getRoutesList(routes, pre) {
      return routes.reduce((array, route) => {
        const path = `${pre}${route.path}`;
    
        if (route.path !== '*') {
          array.push(path);
        }
    
        if (route.children) {
          array.push(...getRoutesList(route.children, `${path}/`));
        }
    
        return array;
      }, []);
    }
    
    getRoutesList(router.options.routes, 'https://zigamiklic.com');
    

    示例输出:

    [
       'https://zigamiklic.com/home',
       'https://zigamiklic.com/settings/',
       'https://zigamiklic.com/settings/general',
       'https://zigamiklic.com/settings/profile',
       'https://zigamiklic.com/contact',
    ]
    

    如果不需要前缀,可以这样使用:

    getRoutesList(router.options.routes, '');
    

    【讨论】:

      猜你喜欢
      • 2016-08-29
      • 2010-09-06
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 2017-03-06
      • 2021-05-21
      • 2016-07-07
      • 1970-01-01
      相关资源
      最近更新 更多