本文单纯的实现路由动态添加功能。
frist of all :
引入脚手架等一些网上都有教材的繁琐事,直到成功的打开页面,如下(自己做的一个登录页面)
then:
选择你的父组件(用来装 动态son )我这里就选择 Vue-cli 自带的组件HelloWorld 如下:
我是酱紫做的:
first one : 新建了一个名叫 view 文件夹 用来装 子路由们sons
于是我就创建了这么几个文件
在各个文件添加了一些东西就开始创建动态路由啦。
这里我们编写一些数据,用来渲染页面的,比如这样|,注意数据必须是这种格式的,因为实力有限,不会写一些方法,方法是copy网上的。
first two :
var children = this.util.extendRouters(this.MenuBarlist);
// this.util.extendRouters() 这个是过滤数据的,是自己码的方法
children.forEach(element => {
// 循环遍历 把每一项都 push 到我们预先准备好的对象里
// this.$router.options.routes[0].children
this.$router.options.routes[0].children.push(element);
})
util.extendRouters() 方法如下,搭建在如下 ,自己创建。
import Vue from 'vue';
let util = {
title:function (title) {
title = title ? title + ' | 统一管理平台' : '统一管理平台';
window.document.title = title;
},
S4:function () {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
},
//产生唯一ID
guid:function () {
return (util.S4()+util.S4()+util.S4()+util.S4()+util.S4()+util.S4()+util.S4()+util.S4());
},
getRootPath:function () {
//获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp
let curWwwPath=window.document.location.href;
//获取主机地址之后的目录,如: uimcardprj/share/meun.jsp
let pathName=window.document.location.pathname;
let pos=curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8083
return curWwwPath.substring(0,pos);
},
extendRouters:function(data) {
let child = new Array(0);
for (let item in data) {
if (data.hasOwnProperty(item)) {
if (data[item].authUrl) {
child.push(
{
path: data[item].authUrl,
component: resolve => {
require.ensure([], (require) => {
resolve(require('../components/view' + data[item].authUrl + '.vue'))
})
}
}
);
}
if (data[item].list && data[item].list.length > 0) {
for (let childItem in data[item].list) {
if (data[item].list.hasOwnProperty(childItem) && data[item].list[childItem] && data[item].list[childItem].authUrl) {
child.push(
{
path: data[item].list[childItem].authUrl,
component: resolve => {
require.ensure([], (require) => {
resolve(require('../components/view' + data[item].list[childItem].authUrl + '.vue'))
})
}
}
);
}
}
}
}
}
//匹配不到
child.push({path: '*', component: Vue.extend({template: '<div>404 page not found</div>'})});
return child;
},
replaceAll:function(src,f,e) {
let reg=new RegExp(f,"g"); //创建正则RegExp对象
return src.replace(reg,e);
}
};
export default util;
push 进去后打印如下:
可以看到数据都 push 进去了
caveat: 不要以为现在就可以输入路径访问组件然后下班回家看花千骨了。
请在 push 完后 添加代码:
this.$router.addRoutes(this.$router.options.routes);
// 此代码可以让你放飞自我,回家看花千骨,其作用相当于注册组件,让你能够安心访问页面,起根本作用我不知道,反正就是你不添加这行代码你就是不能访问页面```
做好这一期准备后在页面上给每个需要点击展示的元素添加事件:
methods: {
replace(index){
// this.MenuBarlist[index.split('-')[0]].list[index.split('-')[1]].authUrl 这行代码表示 当前点击的那一项的 authUrl 值 ,也就是路径
this.$router.push(this.MenuBarlist[index.split('-')[0]].list[index.split('-')[1]].authUrl);
},
},
成功啦!