Vue实现一个简单路由
class Router{
constructor(){
this.routes = new Map(); //维护一个路由表
this.currentUrl = ''; //当前路径
this.bind(); //绑定事件
}
bind(){
//针对浏览器第一次输url的情况
window.addEventListener('load',this.refresh.bind(this),false);
//针对浏览器改变url的情况
window.addEventListener('hashchange',this.refresh.bind(this),false);
}
route(path,callback){
//添加路由,并设置访问该路由的回调函数
this.routes.set(path,callback);
}
replace(path){ //切换路由
this.currentUrl = path;
this.routes.get(path)(); //执行添加路由时设置的回调函数
location.hash = path; //切换路由的时候要修改url
}
refresh(){ //刷新,从url中获取当前路由
this.currentURL = location.hash.slice(1) || '/one';
if(this.currentURL == '/') this.currentURL = '/one';
this.routes.get(this.currentURL)();
}
}
html部分:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script src="route.js"></script>
<style>
ul{
list-style: none;
display: block;
overflow: hidden;
}
ul li{
float:left;
margin-left:10px;
cursor: pointer
}
</style>
</head>
<body>
<div id="app">
<ul>
<li @click="$router.replace('/one')">1</li>
<li @click="$router.replace('/two')">2</li>
<li @click="$router.replace('/three')">3</li>
</ul>
<div :is="currentComponent">
</div>
</div>
<script>
Vue.component('tab-1', {
template: '<div>1 component</div>'
})
Vue.component('tab-2', {
template: '<div>2 component</div>'
})
Vue.component('tab-3', {
template: '<div>3 component</div>'
})
new Vue({
el: '#app',
data(){
return {
test:2,
currentComponent:'tab-1',
'$route':''
}
},
created(){
var router = new Router();
router.route('/one',()=>{
this.currentComponent = 'tab-1';
})
router.route('/two',()=>{
this.currentComponent = 'tab-2';
})
router.route('/three',()=>{
this.currentComponent = 'tab-3';
})
this.$router = router;
}
})
</script>
</body>
</html>