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