路由的基本实现——hash路由
问题提出vue、react在路由的实现上,都有基于hash的路由。那么如何使用原生来实现呢?比如类似下面这样的路由:hashchange事件是实现路由的核心hash实现路由的时候,最本质的原理就是hash值的变化,会引发一个hashchange事件,可以根据这个hash值的变化,加载不同的DOM。html:<div class="box flex-box"&
·
问题提出
vue、react在路由的实现上,都有基于hash的路由。那么如何使用原生来实现呢?
比如类似下面这样的路由:
hashchange事件是实现路由的核心
hash实现路由的时候,最本质的原理就是hash值的变化,会引发一个hashchange事件,可以根据这个hash值的变化,加载不同的DOM。
html:
<div class="box flex-box">
<span class="flex1 center route">home</span>
<span class="flex1 center route">shop</span>
<span class="flex1 center route">shopcar</span>
<span class="flex1 center route">usercenter</span>
</div>
<div id="root"></div>
js:
//路由配置
const routes = [{
path:'/0',
template:'<div>00000000</div>'
},{
path:'/1',
template:'<div>11111111</div>'
},{
path:'/2',
template:'<div>22222222</div>'
},{
path:'/3',
template:'<div>33333333</div>'
}]
//基本实现
var mount = document.getElementById('root');
var list = document.getElementsByClassName('route');
for(var i = 0; i < list.length; i++){
list[i].onclick = (function(i){
return function(){
//console.log(window.location,i);
window.location.hash=`/${i}`;
}
})(i)
}
window.addEventListener('hashchange',function(e){
console.log(e.newURL.split('#')[1]);
var path = e.newURL.split('#')[1];
var item = routes.find(function(item){
return item.path == path;
});
mount.innerHTML = item.template;
})
完整示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<style>
.flex-box{
display: flex;
}
.flex1{
flex: 1;
}
.center{
display: flex;
align-items: center;
justify-content: center;
}
.box{
height: 100px;
}
.route{
border: 1px solid #ccc;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="box flex-box">
<span class="flex1 center route">home</span>
<span class="flex1 center route">shop</span>
<span class="flex1 center route">shopcar</span>
<span class="flex1 center route">usercenter</span>
</div>
<div id="root"></div>
</body>
<script>
const routes = [{
path:'/0',
template:'<div>00000000</div>'
},{
path:'/1',
template:'<div>11111111</div>'
},{
path:'/2',
template:'<div>22222222</div>'
},{
path:'/3',
template:'<div>33333333</div>'
}]
</script>
<script>
var mount = document.getElementById('root');
var list = document.getElementsByClassName('route');
for(var i = 0; i < list.length; i++){
list[i].onclick = (function(i){
return function(){
//console.log(window.location,i);
window.location.hash=`/${i}`;
}
})(i)
}
window.addEventListener('hashchange',function(e){
console.log(e.newURL.split('#')[1]);
var path = e.newURL.split('#')[1];
var item = routes.find(function(item){
return item.path == path;
});
mount.innerHTML = item.template;
})
</script>
</html>
更多推荐
已为社区贡献11条内容
所有评论(0)