深入理解vue-router原理
说到vue-router就表明他只适合于vue和vue是强绑定的关系;不适合其他框架;
现在我们模仿实现一个VueRouter;
1.要使页面刷新;借助vue本身的响应式原理;
import Home from "./views/Home";
import About from "./views/About";
import Vue from "vue";
class VueRouter{
constructor(options){
this.$options = options;
this.routeMap = {}
// 路由响应式 其实很重要的一部分是借助了 vue 的响应式原理 ; 强绑定 ; 必须用在vue上
this.app = new Vue({
data:{
current:"/"
}
})
}
}
VueRouter.install=function(Vue){
//mixin 混入
Vue.mixin({
beforeCreate() {
// this 是vue 实咧
if(this.$options.router){ // 只在跟组件执行一次
Vue.prototype.$router = this.$options.router;
this.$options.router.init()
}
},
})
}
Vue.use(VueRouter)
export default new VueRouter({
routes: [{ path: "/", component: Home }, { path: "/about", component: About }]
})
2.执行上面的init函数;初始化
//这里主要三件事;监听url变化;解析路由配置;实现两个组件
init(){
this.bindEvents() ; //监听url变化
this.createRouteMap(this.$options) ; //解析路由配置
this.initComponent() ; //实现两个组件 router-view router-link
}
3.监听url变化;更新数据
bindEvents(){
window.addEventListener('load',this.onHashChange.bind(this))
window.addEventListener('hashchange',this.onHashChange.bind(this))
}
onHashChange(){
this.app.current = window.location.hash.slice(1) || '/'; // #/about ==> /about
}
4.解析路由配置;
//这个好理解;就是把传进来的路由配置;解析成path-->component的key:value形式
createRouteMap(options){
options.routes.forEach(item=>{
this.routeMap[item.path] = item.component
})
}
5.实现router-link 和 router-view两个组件
initComponent(){
// router-view router-link
Vue.component('router-link',{
props:{to:String},
render(h) {
// h => createElement h(tag,data,children)
return h('a',{attrs:{href:'#'+this.to}},[
this.$slots.default
])
},
});
Vue.component('router-view',{ //这里没有解决路由嵌套的问题 // 全局的组件 任意data 的都会出发全局组件的跟新
render:h=>{
console.log(this.routeMap[this.app.current])
const comp = this.routeMap[this.app.current]
return h(comp)
},
})
}
vue-router的hash模式主要就是监听了hashchange方法;改变当前的路径,再利用vue自身的响应式原理;来刷新视图;
vue-history模式;要服务器配合;访问进来是指向同一个html;代码上处理原理我想和hash应该类似;大家可以自己研究一下;
人到了一定的年龄,一定要懂得,把心情和脾气调成静音模式,然后不动声色的打理自己,过好余生每一天。一路风雨兼程,只为遇见更好的自己,真正能够带你走出黑暗,能够给你带来改变的,就是你自己的内心自信,光明,有拯救自己的责任感动力