yoho-plugin-router.js 1.6 KB
import Router from 'vue-router';
import config from 'config';
import pageRoutes from '../pages';
import layout from '../pages/layout';
import common from '../pages/common';
import _ from 'lodash';

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

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

            if (rous.children) {
                _.each(rous.children, child => this.loadRouters(child, [paths, child.name], true));
                return [rous];
            }
            return [rous];
        }
        if (rous.length) {
            return _.map(rous, r => {
                return this.loadRouters(r, [paths]);
            });
        } else {
            return _.map(rous, (rou, k) => {
                return this.loadRouters(rou, [paths, k]);
            });
        }
    },
    install(Vue) {
        let childRouters = this.loadRouters(pageRoutes);
        console.log(_.flattenDeep(childRouters))
        let routes = [{
            path: '/',
            component: layout,
            children: _.flattenDeep(childRouters)
        }];

        routes = routes.concat(common);
        Vue.$router = new Router({
            routes: routes,
            mode: config.historyMode
        });
    }
};

export default plugin;