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

vue系列--实现一个简单的vue-router

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

一个简单的vue路由实现首先要确定我们要做的功能点。VueRouter是一个插件。必须有一个install方法来实现router-view和router-link。两个组件都要监听url的变化,hash方式要监听hashchange事件。history模式需要监听popstate事件根据不同的路由变化显示不同的组件1.声明classSimpleVueRouter{}2.注册install方法并接收VueclassSimpleVueRouter.install=function(_Vue){//Vue是js里面的一个变量,_Vue是真正的Vue类Vue=_Vue;}3.编写SimpleVueRouter的构造函数,保存传入的路由配置选项,声明一个路由对应关系,为响应类声明一个Vue实例对象SimpleVueRouter{constructor(options){this.$options=options;this.routeMap={};this.app=newVue({data(){return{current:'/'}}});}}4.在SimpleVueRouter类的init方法中添加,在install方法中为Vue注册mixin,在Vue中添加$router并执行init方法。为什么要使用mixins,因为我们需要在当前Vue实例上挂载VueRouter的实例对象,但是在Vue.use的时候,实例对象还没有生成,必须在实例对象已经生成之后才生成,所以注册一个全局mixin,方便初始化时挂载VueRouter实例//添加install方法,SimpleVueRouter会在Vue.use时执行。install=function(_Vue){Vue=_Vue;Vue.mixin({beforeCreate(){/***this是Vue的实例对象*this.$options是newVue()时传入的参数*只有main.js会有路由器项,所以if只会输入一次**/if(this.$options.router){this.$router=this.$options.router;this.$options.router.init();}}});}5.监听浏览器的hashChange和load方法事件,修改this.app.currentinitEvent(){//监听浏览器的hashchange和load事件,使用bind将this指向window.addEventListener('hashchange',this.handleHashChange.bind(this));window.addEventListener('load',this.handleHashChange.bind(this));}handleHashChange(){//获取#给应用当前赋值后的部分this.app.current=location.hash.slice(1);}6.注册路由对应initRouteMap(){this.$options.routes.forEach(item=>{this.routeMap[item.path]=item;});}7.注册s-router-link和s-router-view组件registerComponents(){//router-link默认显示一个标签,用于点击跳转Vue.component('s-router-link',{props:{to:String,required:true,},render:function(h){returnh('a',{attrs:{href:`#${this.to}`}},this.$slots.default)};}});//router-view是一个容器,可以显示当前路由对应的组件Vue.component('s-router-view',{render:h=>{//这里使用了箭头函数,为了让这个指向当前路由器实例而不是vue实例constcom=this.routeMap[this.app.current].component;returnh(com)}});}8.在init方法init()中初始化事件、路由和组件{this.initEvent();这个.initRouteMap();这个.registerComponents();}9.使用方法importSimpleVueRouterfrom'./simple-vue-router';从“vue”导入Vue;从'./components/com1'导入Com1;从'./components/com2'导入Com2;从'./components/home'导入Home;Vue.use(SimpleVueRouter);导出默认新SimpleVueRouter({routes:[{path:'/',component:Home},{path:'/com1',component:Com1},{path:'/com2',component:Com2}]});整个idea过程就是注册插件,监听浏览器的hash变化事件,修改某个vue实例的某个属性,利用vue的响应式,使用的地方也会发生变化,从而更新router-view显示的地方。需要准备的知识包括:如何注册vue插件,如何注册组件的vuemixinrender功能的使用本例只实现了简单的路由跳转和使用hash的展示。如果读者对其他方法感兴趣,可以自行实现github地址。