原生js实现简单路由

<!DOCTYPE html>
<html>
<head>
<title>这是一个测试文件</title>
<meta name="viewport" content="width=device-width,initial-scale=no,maximum-scale=1.0,minimum-scale=1.0,
user-scalable=no">
</head>
<body>

<script type="text/javascript">

function Router(){
this.router = [];//路由数组

}

Router.prototype.route = function(routePath, fun) {
//第一个参数是路由路径,第二个参数是回调函数
this.router.push({
path: routePath,
callBack: fun
})
}


Router.prototype.validate = function() {
var [currentPath, ...a] = [...arguments];
//进行比较当前的路由地址和已经保存的路由地址,如果存在,则调用相应的回调函数
this.router.forEach(item => {
if(currentPath == item.path){
item.callBack.apply(null, arguments);
}
})
}


window.addEventListener("hashchange",function(){
var a = window.location.hash.slice(1);//获得路由规则
//把当前的路由规则和完整的url地址传进去
myRouter.validate(a,window.location.href);
},false);

var myRouter = new Router();

myRouter.route("/", function(routePath){
//里面的this指向window,如果要指向Router的对象,在validate函数里面修改null为this
console.log("这是路由入口");
})


//下面设置4个路由,用于增删改查操作
myRouter.route("/select", function(){
var a = [...arguments];
//console.log(a)打印出当前的路由规则和完整的url,具体想要传入的参数可以在ashchange侦听函数中设置
console.log("这是查找路由");
})
myRouter.route("/edit", function(){
console.log("这是编辑路由");
})
myRouter.route("/add", function(r){

console.log("这是添加路由");
})
myRouter.route("/del", function(){
console.log("这是删除路由");
})

//这里可以添加更多的路由规则和回调函数

</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值