为了账号安全,请及时绑定邮箱和手机立即绑定

实现手写简单VueRouter源码

标签:
Vue.js

要求

  1. 必须有一个install方法,供Vue.use调用
  2. 实现hash变化,响应式数据自动更新
	let Vue;
	class VueRouter{
		constructor(options){
			this.$options = options;
			this.routeMap = {};//缓存route 和 path 的映射关系
			this.$options.routes.forEach(route=>{
				this.routeMap[route.path] = route
			})
			const initial = window.location.hash.slice(1) || '/';
			//实现current 响应式,发生变化更新所有引用current的渲染
			Vue.util.defineReactive(this,'current',initial)
			//监听hash变化
			window.addEventListener('hashchange',()=>{
				//使用箭头函数,this指向不变
				this.current  = window.location.hash.slice(1)
			})
			//每次重新进入页面时执行
			window.addEventListener('load',()=>{
				this.current = window.location.hash.slice(1)
			})
		}
	}
	VueRouter.install = function(_Vue){
		Vue = _Vue;
		//使用混入 延迟执行到router创建完毕才执行
		Vue.mixin({
			//每个vue组件实例化都会执行一遍
			beforeCreate(){
				if(this.$options.router){
					//只有main.js 根组件实例化时才会有router选项
					Vue.prototype.$router = this.$options.router
				}
			}
		})
		Vue.component('router-link',{
			props:{
				to:{
				type:String,
				required:true
				}
			},
			render(h){
				return h('a',{attrs:{href:'#'+this.to}},this.$slots.default)
			}
		})
		Vue.component('router-view',{
			render(h){
				let {routeMap,current} = this.$router;
				let component = routeMap[current]?routeMap[current].component:null;
				return h(component)
			}
		})
	}
	export default VueRouter
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
28
获赞与收藏
163

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消