1. 程式人生 > 實用技巧 >實現手寫簡單VueRouter原始碼

實現手寫簡單VueRouter原始碼

要求

  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