index.js 1.26 KB
import Vue from 'vue';
import Router from 'vue-router';
import pages from '../pages';
import _ from 'lodash/core';

Vue.use(Router);

const loadRoutes = (rous, paths, children) => {
  if (_.has(rous, 'path')) {
    let ps = _.flattenDeep(paths).filter(p => p);

    if (_.last(ps) === rous.name) {
      ps.splice(ps.length - 1, 1);
    }
    if (!children) {
      if (rous.path) {
        rous.path = ps.join('/') + (rous.path[0] === '/' ? '' : '/') + rous.path;
      } else {
        rous.path = ps.join('/') + '.html';
      }
    }
    rous.name = _.concat(ps, [rous.name]).join('.');

    if (rous.children) {
      _.each(rous.children, child => loadRoutes(child, [paths, child.name], true));
      return [rous];
    }
    return [rous];
  }
  if (rous.length) {
    return _.map(rous, r => {
      return loadRoutes(r, [paths]);
    });
  } else {
    return _.map(rous, (rou, k) => {
      return loadRoutes(rou, [paths, k]);
    });
  }
};

export function createRouter() {
  const routes = _.flattenDeep(loadRoutes(pages));

  const router = new Router({
    mode: 'history',
    routes,
    scrollBehavior(to, from, savedPosition) {
      if (savedPosition) {
        return savedPosition;
      } else {
        return { x: 0, y: 0 };
      }
    }
  });

  return router;
}