自定义插件vue-router简单实现hashRouter设计思路

本文主要是介绍自定义插件vue-router简单实现hashRouter设计思路,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

步骤

1.挂载 vue.prototype.$router

2.声明两个组件

router-view this.$router.current=>component => h(component)

router-link h('a',{attrs:{href:'#'+this.to}},this.$slots.default)

3.url的监听:window hashchange的改变

4.定义响应式current,defineReactive()

实现VueRouter类

let Vue
// vueRouter是一个类,一个插件
class VueRouter {constructor(options) {this.$options = options}
}VueRouter.install = function (_Vue) {//保存引用Vue = _Vue//挂在一下vueRouter到vue原型//利用全局混入,全局执行代码,在vue实例beforeCreate时获取到router,因为在main.js中生成vue实例在VueRouter挂载到Vue之后,所以常规无法获取到router,Vue.mixin({beforeCreate() {if (this.$options.router) { //避免每次实例创建都触发,只有根实例上存在的才触发。Vue.prototype.$router = this.$options.router}}})//声明两个全局组件,router-viewport,router-linkVue.component('router-link', {props: {to: {type: String,required: true}},//预编译情况下,template是不能使用的,这里要使用render// template:'<a>123</a>'render(h) {// return <a href={'#'+this.to}>{this.$slots.default}</a> jsx语法也可以使用return h('a', {attrs: { href: "#" + this.to }}, this.$slots.default) //this.$slots.default 获取内容}})Vue.component('router-view', {render(h) {return h('div', 'router-view')}})
}export default VueRouter

这里有个难点,就是如何将router挂载到vue原型上,我们采用了mixin的用法,在vue实例beforeCreate时获取到router,并挂在到实例上。

怎么理解呢?在router.js中,Vue.use(VueRouter)触发install方法,但是在此时,并没有生成router,是在new VueRouter之后生成的router,并且挂载到了Vue,此时才有VueRouter,利用全局混入,延迟执行挂载到Vue原型上,这样就可以获取到router实例了。

import Vue from 'vue'
// import VueRouter from 'vue-router'
import VueRouter from '@/krouter/kvue-router'
Vue.use(VueRouter)//执行install方法,router还未被创建
const routes = [{path: '/home',name: 'home',component: () => import('@/components/Home.vue')},{path: '/about',name: 'about',component: () => import('@/components/About.vue')},
]const router = new VueRouter({routes
})
export default router
import Vue from 'vue'
import App from './App.vue'
import router from './router/router'Vue.config.productionTip = falsenew Vue({router,render: h => h(App),
}).$mount('#app')

监听url变化,渲染组件

class VueRouter {constructor(options) {this.$options = options//声明一个响应式current//渲染函数如果压重复执行,必须依赖响应式数据Vue.util.defineReactive(this,'current',window.location.hash.slice(1) || '/') //需要#后面的部分//监听url变化window.addEventListener('hashchange', () => {this.current = window.location.hash.slice(1)})}
}

这里使用Vue工具类定义响应式current,必须是响应式current,否则不生效,在router-view处读取并渲染对应组件,在这里Vue的原型对象已经挂载了this.$router,this.$router又是VueRouter的实例,所以在这上面能够找到对应的current属性,所以在current变化的时候,在引用到current的地方都会被通知到,然后渲染组件。

Vue.component('router-view', {render(h) {const obj = this.$router.$options.routes.find(el=>this.$router.current==el.path)return h(obj.component)}})

但是每次都要去遍历循环字典,也不是很合理,我们可以优化一下,缓存一下path和route映射关系

路由嵌套

思路:参考源码思路,给当前routerView深度标记,然后根据当前页面路由获取当前路由数组,其中包括一级和二级路由,然后使用depth获取对应的组件,然后并渲染。

Vue.component('router-view', {render(h) {//标记当前router-view深度this.$vnode.data.routerView = truelet depth = 0let parent = this.$parentwhile (parent) {const vnodeData = parent.$vnode && parent.$vnode.dataif (vnodeData) {if (vnodeData.routerView) {//说明当前的parent是一个routerViewdepth++}}parent = parent.$parent}let component = nullconst route = this.$router.matched[depth]if (route) {component = route.component}return h(component)}})

此时我们不再使用current来做响应式,使用matched数组获取匹配关系,VueRouter实例创建时调用match方法,获取路由数组,并且在路由发生变化时重新获取路由数组matched。

class VueRouter {constructor(options) {this.$options = options//声明一个响应式current//渲染函数如果压重复执行,必须依赖响应式数据// Vue.util.defineReactive(this,'current',window.location.hash.slice(1) || '/') //需要#后面的部分this.current = window.location.hash.slice(1) || '/' //初始值Vue.util.defineReactive(this, 'matched', [])// match方法可以递归的遍历路由表获取匹配关系的数组this.match()//监听url变化window.addEventListener('hashchange', () => {this.current = window.location.hash.slice(1)this.matched=[]this.match()})}match(routes) {routes = routes || this.$options.routesconsole.log(routes);//递归遍历路由表for (const route of routes) {if (this.current.indexOf(route.path)!=-1) {this.matched.push(route)if (route.children) {this.match(route.children)}return}}}
}

附完整代码:

//vue-router插件
let Vue
// vueRouter是一个类,一个插件
class VueRouter {constructor(options) {this.$options = options//声明一个响应式current//渲染函数如果压重复执行,必须依赖响应式数据// Vue.util.defineReactive(this,'current',window.location.hash.slice(1) || '/') //需要#后面的部分this.current = window.location.hash.slice(1) || '/' //初始值Vue.util.defineReactive(this, 'matched', [])// match方法可以递归的遍历路由表获取匹配关系的数组this.match()//监听url变化window.addEventListener('hashchange', () => {this.current = window.location.hash.slice(1)this.matched=[]this.match()})}match(routes) {routes = routes || this.$options.routes//递归遍历路由表for (const route of routes) {if (this.current.indexOf(route.path)!=-1) {this.matched.push(route)if (route.children) {this.match(route.children)}return}}console.log(this.matched);}
}VueRouter.install = function (_Vue) {//保存引用Vue = _Vue//挂在一下vueRouter到vue原型//利用全局混入,全局执行代码,在vue实例beforeCreate时获取到router,因为在main.js中生成vue实例在VueRouter挂载到Vue之后,所以常规无法获取到router,Vue.mixin({beforeCreate() {if (this.$options.router) { //避免每次实例创建都触发,只有根实例上存在的才触发。Vue.prototype.$router = this.$options.router}}})//声明两个全局组件,router-viewport,router-linkVue.component('router-link', {props: {to: {type: String,required: true}},//预编译情况下,template是不能使用的,这里要使用render// template:'<a>123</a>'render(h) {// return <a href={'#'+this.to}>{this.$slots.default}</a> jsx语法也可以使用return h('a', {attrs: { href: "#" + this.to }}, this.$slots.default) //this.$slots.default 获取内容}})Vue.component('router-view', {render(h) {//标记当前router-view深度this.$vnode.data.routerView = truelet depth = 0let parent = this.$parentwhile (parent) {const vnodeData = parent.$vnode && parent.$vnode.dataif (vnodeData) {if (vnodeData.routerView) {//说明当前的parent是一个routerViewdepth++}}parent = parent.$parent}let component = nullconsole.log(this.$router.matched);const route = this.$router.matched[depth]if (route) {component = route.component}return h(component)}})
}export default VueRouter
import Vue from 'vue'
// import VueRouter from 'vue-router'
import VueRouter from '@/krouter/kvue-router'
Vue.use(VueRouter)//执行install方法,router还未被创建
const routes = [{path: '/home',name: 'home',component: () => import('@/components/Home.vue')},{path: '/about',name: 'about',component: () => import('@/components/About.vue'),children: [{path: '/about/info',component: {render(h) {return h('div', 'info page')}}}]},
]const router = new VueRouter({routes
})
export default router

这篇关于自定义插件vue-router简单实现hashRouter设计思路的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/462818

相关文章

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert