当前位置: 首页 > Web前端 > vue.js

vue-router源码详解

时间:2023-03-31 15:37:00 vue.js

登场个人网站《锋言锋语》-vue-router源码详解1beforeCreate在src/install.js文件中使用Vue.mixi混合了两个生命周期处理函数:beforeCreate和destroyed,在beforeCreate中处理了与rooter相关的操作:beforeCreate(){if(isDef(this.$options.router)){this._routerRoot=thisthis._router=this.$options.routerthis._router.init(this)Vue.util.defineReactive(this,'_route',this._router.history.current)}else{this._routerRoot=(this.$parent&&this.$parent._routerRoot)||}this}registerInstance(this,this)},this.$options.routervue中有两种Vue对象:vue实例和vue组件,其中vue实例是newVue创建的vue对象,vue组件是vue对象由Vue.component创建。但本质上“Vue组件是可重用的Vue实例”,“vue实例是特殊的根vue组件”参考资料:Vue实例、组件基础和vm.$options是当前Vue实例的初始化选项。参考资料:实例属性所以只在vue实例中,传入router属性:importVuefrom'vue'importVueRouterfrom'vue-router'Vue.use(VueRouter)constrouter=newVueRouter({mode:'history',routes:[...]})newVue({router,}).$mount('#app')因此,beforeCreate中的代码分别为根vue组件和普通vue组件的_routerRoot的定义:if(isDef(this.$options.router)){this._routerRoot=thisthis._router=this.$options.routerthis._router.init(this)Vue.util.defineReactive(this,'_route',this._router.history.current)}else{this._routerRoot=(this.$parent&&this.$parent._routerRoot)||this}我们在组件中使用this.$router,也就是返回_routerRoot属性的_router:Object.defineProperty(Vue.prototype,'$router',{get(){returnthis._routerRoot._router}})和this.$route是返回_routerRoot的_router属性:Object.defineProperty(Vue.prototype,'$route',{get(){returnthis._routerRoot._route}})this.$route和this.$router的区别通过beforeCreate中的代码可以得到:this._router是传入的router属性的值,即newVueRouter返回的是VueRouter对象this._routerRoot._route只是this._routerRoot._router中的history.current属性值接下来我们看看this._router.history是什么对象?exportdefaultclassVueRouter{构造函数(选项:RouterOptions={}){letmode=options.mode||'hash'开关(模式){case'history':this.history=newHTML5History(this,options.base)breakcase'hash':this.history=newHashHistory(this,options.base,this.fallback)breakcase'abstract':this.history=newAbstractHistory(this,options.base)breakdefault:if(process.env.NODE_ENV!=='production'){assert(false,`无效模式:${mode}`)}}}}通过VueRouter的构造函数我们可以看到this._router.history在不同的场景下代表不同的对象,HTML5History,HashHistory或者AbstractHistory对象上面三个***History类都是继承自History类:declaretypeRoute={path:string;名称:?字符串;哈希:字符串;查询:字典<字符串>;参数:字典<字符串>;全路径:字符串;匹配:数组;重定向自?:字符串;meta?:any;}exportclassHistory{current:Route}可以看出this.$route即this._routerRoot._route是当前页面url的一些基本属性,而this.$router代表整个vuerouter对象,所以使用了更多的push、replace、go等路由操作。