亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

實現手寫簡單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下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消