hash值得改变不会刷新页面, 监听hashchange事件根据不同的路由渲染页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>SPA</title>
</head>
<body>
<a href="#/index">index</a>
<a href="#/login">login</a>
<div id="routerContent"></div>
</body>
<script type="text/javascript">
//router类
class Router{
constructor(){
this.router={};
}
renderRoute(path,callback){
//保存路由信息
this.router[path] = {name:path,callback};
//调用回调
callback.call(this, this.router[path], this.router)
}
}
let router = new Router();
//监听hashchange
window.addEventListener("hashchange", render);
function render(e) {
let hash = e.newURL.substr(e.newURL.indexOf("#")+2)
router.renderRoute(hash,(route, router)=>{
routerContent.innerHTML=route.name
})
}
</script>
</html>
评论 (0)