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

VueRouter模拟实现

时间:2023-03-31 15:31:19 vue.js

Vue-Router哈希方式URL中#后面的内容作为路由地址监听hashchange事件,根据当前路由和地址找到对应的组件。重新渲染历史模式,通过history.pushState()方法更改地址栏。组件重渲染的基本使用//1.注册路由插件Vue.use(VueRouter)//2.创建路由对象constrouter=newVueRouter({routes:[{nmae:'home',path:'/',component:homeComponent}]})constvm=newVue({//3.注册路由器对象router,render:h=>h(App)}).$mount('#app')第一步实现install方法第二步实现构造函数。在构造函数中,需要初始化options、data、routeMap这三个属性。数据是响应对象。第三步,实现createRouteMap方法,将构造函数中options传入的路由构造成键值对存储在routeMap中,key为路由地址,value为组件。第四步是实现initComponents方法。第五步,运行时版本Vue不支持模板。手动实现渲染功能。第六步,执行initEvent()方法/*eslint-disableindent*/let_VueexportdefaultclassVueRouter{//首先执行install方法//1、判断当前插件是否已经安装staticinstall(Vue){if(VueRouter.install.installed){return}VueRouter.install.installed=true//2、记录Vue构造函数到全局变量_Vue=Vue//3、注入传入的router对象,创建Vue实例进入Vue实例//混合在_Vue.mixin({beforeCreate(){if(this.$options.router){//只需要执行一次,只有当它是vue实例时才会执行。组件options中没有router属性_Vue.prototype.$router=this.$options.router//this.$options.router.init()//调用并初始化两个方法}}})}//第二个step是实现constructorconstructor(options){this.options=optionsthis.routeMap={}//解析options中存储的路由,key为路由地址,value为组件this.data=_Vue.observable({current:'/'})this.init()}//第三步实现createROuteMapcreateRouteMap(){//遍历所有路由规则,解析路由规则以键值对的形式存储在routeMap中this.options.routes.forEach(route=>{this.routeMap[route.path]=route.component})}init(){this.createRouteMap()this.initComponents(_Vue)this.initEvent()}initComponents(Vue){//实现路由链接组件Vue.component('router-link',{props:{to:String},//template:''运行时版本vue不支持templatetemplaterender(h){returnh('a',{attrs:{href:this.to},on:{click:this.clickHandler//防止点击的默认行为}},[this.$slots.default])},methods:{clickHandler(e){history.pushState({},'',this.to)//改变当前路由地址this.$router.data.current=this.toe.preventDefault()}}})constself=thisVue.component('router-view',{render(h){constcomponent=self.routeMap[self.data.current]returnh(component)//将组件转换为虚拟dom}})}initEvent(){//注册popstate事件window.addEventListener('popstate',()=>{//这表示组件实例this.data.current=window.location.pathname})}}