路由的跳转原理(哈希模式)
window.addEventListener('hashchange', function(e) {
console.log(e)
})
核心是锚点值的改变,我们监听到锚点值改变了就去局部改变页面数据,不做跳转。跟传统开发模式url改变后 立刻发起请求,响应整个页面,渲染整个页面比路由的跳转用户体验更好
代码测试如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>路由跳转原理</title>
</head>
<body>
<a href="#/Login">登录</a>
|
<a href="#/Register">注册</a>
<div id="app"></div>
<script type="text/javascript">
var appdiv=document.getElementById('app')
//监控页面
window.addEventListener('hashchange',function(e){
console.log(location.hash)
switch(location.hash){
case '#/Login':
//更新div数据
appdiv.innerHTML='我是登录界面'
break
case '#/Register':
appdiv.innerHTML='我是注册界面'
break
}
})
</script>
</body>
</html>