<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>router</title>
</head>
<body>
<ul>
<li><a href="#/">turn white</a></li>
<li><a href="#/blue">turn blue</a></li>
<li><a href="#/green">turn green</a></li>
</ul>
<script>
// 路由类
function Router(){
this.routes = {}
this.currentUrl = ''
}
Router.prototype = {
constructor: Router,
router: function(data){
for(var item of data){
this.routes[item.path] = item.getComponent || function (){}
}
},
refresh: function(){
console.log(this)
this.currentUrl = location.hash.slice(1) || '/'
this.routes[this.currentUrl]()
},
init: function (){
window.addEventListener('load',this.refresh.bind(this),false)
window.addEventListener('hashchange',this.refresh.bind(this),false)
}
}
window.Router = new Router()
// 注册路由改变事件
window.Router.init()
var content = document.querySelector('body')
function changeBgColor(color){
content.style.backgroundColor = color
}
var routes_data = [
{
path: '/',
getComponent: function(){
changeBgColor('white')
}
},
{
path: '/blue',
getComponent: function(){
changeBgColor('blue')
}
},
{
path: '/green',
getComponent: function(){
changeBgColor('green')
}
},
]
// 注册路由表
Router.router(routes_data)
</script>
</body>
</html>
原文地址https://github.com/joeyguo/blog/blob/master/lab/2016/router/simple-router.html
网友评论