See all posts

Simple Sitemap For Vue Router

January 7, 2019
2 min

A client wanted me to send her all the links for an app which uses Vue with Vue Router. At first, I tried to compose the list by hand – the app has only 45 links. But after a while decided it would be easier to do it with Javascript. And even more useful if I get the same request in the future.

In my case, I only needed a simple list of all the links to send to the client. I then also decided to expand my solution to output the list in sitemap XML format.

Note that the below solutions are for simple use cases like mine. If you need a real sitemap, I recommend installing an NPM package like vue-router-sitemap.

Simple List

The getRoutesList function below returns an array with all the routes for your app:

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',
]

The first parameter of the getRoutesList function requires the options.routes array that is available on the Router instance. The second is the URL prefix for all the routes.

For my use case I placed the code inside my router file (router/index.js) and used console.log around the function call to display the routes.

If you want to use the function inside a component (eg. inside mounted), change the first parameter to this.$router.options.routes.

XML Format

The getRoutesList can also be used to also generate XML sitemap format:

function getRoutesXML() {
  const list = getRoutesList(router.options.routes, 'https://zigamiklic.com')
    .map(route => `<url><loc>${route}</loc></url>`)
    .join('\r\n');
  return `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    ${list}
  </urlset>`;
}

getRoutesXML();

The getRoutesXML uses the previous function and makes modifications to its output. It wraps all the routes in <url><loc> tags by using the map array method. Then by using join, it converts the array to a string with each route on its own line.

The function’s return statement includes the <urlset> with all the required attributes for sitemap XML format.

Previous Adding a custom loader in a Vue CLI app Next Empty An Array Without Losing Reference