自定义插件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

相关文章

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方