// 创建一个全局变量,用来保存vue的构造函数
let vue;
class KVueRouter{
constructor(options){
this.$options = options;
}
}
// 1.实现插件
// 在使用插件时,会把vue的构造函数当成参数传进来
KVueRouter.install = function(_vue){
Vue = _vue; //保存构造函数,在KVueRoutero里面使用
// 使用mixin获取根实例上的router选项
Vue.mixin({
beforeCreate() {
console.log(this);
// 确保根实例时,才执行挂载
if(this.$options.router){
Vue.prototype.$router = this.$options.router;
}
}
})
// 2.实现router-link组件
Vue.component('router-link',{
props:{
to:{
required:true
}
},
// 不能使用template来,因为不能在只有运行时版本时候使用template,而是使用render
render(h){
// <a href='#/about'>关于</a>
let path = ''
if(typeof this.to === 'string'){
path = this.to
}else if(typeof this.to === 'object'){
path = '/'+this.to.name
}
console.log(this.$slots); //当前组件的插槽集合,default:[Vnode]为其默认插槽内容
return h('a',{attrs:{href:'#' + path}},this.$slots.default) //里面的内容使用一个匿名插槽
}
})
// 3.实现router-view组件
Vue.component('router-view',{
render(h){
const {routeMap,curPath} = this.$router; //获取路由映射表,和当前路由值
let component = routeMap[curPath] || null
return h(component)
}
})
}
export default KVueRouter;
vue router实现的源码
最新推荐文章于 2024-07-18 13:56:07 发布