import Vue from 'vue'
export default class vueRouter{ // 声明一个vueRouter类
constructor (options){ // 参数就是你传进来的路由对象
this.$options = options;
this.routerMap = {};
this.app = new Vue({// 主要是利用vue的响应式原理
data:{ // 这两种方法都可以
current:'/'
}
// data () { // data在组件里使用必须是一个函数 因为组件可以会生成多个实例 如果data仍然是一个纯粹的对象,则所有的实例将共享引用同一个数据对象
// return{
// current:'/'
// }
// }
})
}
init () {
this.bindEvents();// 监听事件
this.createRouteMap(); // 解析路由
this.initComponet(); //实现组件
}
bindEvents (){
window.addEventListener('load',this.onHashChange.bind(this));//load时触发
window.addEventListener('hashchange',this.onHashChange.bind(this));// 锚发生变化触发也就是#后面发生变化
}
onHashChange () {
this.app.current = window.location.hash.slice(1) || '/'
}
createRouteMap (){
this.$options.routes.forEach(item =>{
this.routerMap[item.path] = item.component;
})
}
initComponet (){
// router link
Vue.component('router-link',{
props:{to:String},
render(h) {
return h('a',{attrs:{href:'#'+this.to}},[this.$slots.default])
}
})
// router view
Vue.component('router-view',{
render:(h)=>{
const comp = this.routerMap[this.app.current] // this.app.current 发生变化 组件就会发生变化
return h(comp)
}
})
}
}
vueRouter.install = function(Vue){ //声明一个install方法 这个方法接受一个vue实例
Vue.mixin({ // 混入
beforeCreate() { // 所有组件的这个生命周期钩子 执行的时候
if(this.$options.router){ // 组件如果有这个router
Vue.prototype.$router = this.$options.router
this.$options.router.init(); //执行初始化方法
}
}
})
}
网友评论