javascript - 如何从vue路由器中仅提取路由来生成站点地图

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

我有一个导出我的 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 :

node --experimental-modules test.js

但是我遇到了这个错误:

$ node --experimental-modules test.js (node:13688) ExperimentalWarning: The ESM module loader is experimental. 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: Unexpected identifier at new Script (vm.js:80:7) at createScript (vm.js:274:10) at Proxy.runInThisContext (vm.js:326:10) at Module._compile (internal/modules/cjs/loader.js:664:28) at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10) at Module.load (internal/modules/cjs/loader.js:600:32) at tryModuleLoad (internal/modules/cjs/loader.js:539:12) at Function.Module._load (internal/modules/cjs/loader.js:531:3) at createDynamicModule (internal/modules/esm/translators.js:73:15) at Object.meta.done (internal/modules/esm/create_dynamic_module.js:42:9)

问题

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

最佳答案

有一个关于这个的例子 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');

Example output:

[
   '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, '');

关于javascript - 如何从vue路由器中仅提取路由来生成站点地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199603/

相关文章:

javascript - Heroku nuxt 生产部署使用暂存配置变量

javascript - 从 html 页面打印表格

javascript - 在粒子系统中渲染球体(或点)

javascript - 通过 Node.js 将客户端表单输入发送到服务器端数据库查询并将结果返回给客户端

node.js - Docker容器中的Node.js应用尝试连接到其他Docker容器中的mongodb时出错

vue.js - 我有一个 Electron 项目,我想与它一起使用vueJS

javascript - 为什么这些子项没有在 TS 中呈现为数组?

javascript - $() 函数未按预期工作

javascript - Nodejs 卡住 MySQL 大量结果输入 REDIS HMSET

unit-testing - 单元测试 Vue JS 和 Vue Resource 时状态不变