前端路由简介以及vue-router实现原理
ztj100 2024-12-29 07:22 39 浏览 0 评论
作者:muwoo
来源:https://zhuanlan.zhihu.com/p/37730038
后端路由简介
路由这个概念最先是后端出现的。在以前用模板引擎开发页面时,经常会看到这样
http://www.xxx.com/login
大致流程可以看成这样:
- 浏览器发出请求
- 服务器监听到80 端口(或443)有请求过来,并解析 url 路径
- 根据服务器的路由配置,返回相应信息(可以是 html 字串,也可以是 json 数据,图片等)
- 浏览器根据数据包的 Content-Type 来决定如何解析数据
简单来说路由就是用来跟后端服务器进行交互的一种方式,通过不同的路径,来请求不同的资源,请求不同的页面是路由的其中一种功能。
前端路由
- hash 模式
随着 ajax 的流行,异步数据请求交互运行在不刷新浏览器的情况下进行。而异步交互体验的更高级版本就是 SPA —— 单页应用。单页应用不仅仅是在页面交互是无刷新的,连页面跳转都是无刷新的,为了实现单页应用,所以就有了前端路由。
类似于服务端路由,前端路由实现起来其实也很简单,就是匹配不同的 url 路径,进行解析,然后动态的渲染出区域 html 内容。但是这样存在一个问题,就是 url 每次变化的时候,都会造成页面的刷新。那解决问题的思路便是在改变 url 的情况下,保证页面的不刷新。在 2014 年之前,大家是通过 hash 来实现路由,url hash 就是类似于:
http://www.xxx.com/#/login
这种# 。后面 hash 值的变化,并不会导致浏览器向服务器发出请求,浏览器不发出请求,也就不会刷新页面。另外每次 hash 值的变化,还会触发 hashchange 这个事件,通过这个事件我们就可以知道 hash 值发生了哪些变化。然后我们便可以监听 hashchange来实现更新页面部分内容的操作:
unction matchAndUpdate () {
// todo 匹配 hash 做 dom 更新操作
}
window.addEventListener('hashchange', matchAndUpdate)
Vue router 实现
我们来看一下vue-router 是如何定义的:
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
routes: [...]
})
new Vue({
router
...
})
可以看出来 vue-router 是通过Vue.use 的方法被注入进 Vue 实例中,在使用的时候我们需要全局用到 vue-router 的router-view 和 router-link 组件,以及 this.$router/$route 这样的实例对象。那么是如何实现这些操作的呢?下面我会分几个章节详细的带你进入 vue-router的世界。
造轮子 -- 动手实现一个数据驱动的 router
经过上面的阐述,相信您已经对前端路由以及vue-router 有了一些大致的了解。那么这里我们为了贯彻无解肥,我们来手把手撸一个下面这样的数据驱动的 router:
new Router({
id: 'router-view', // 容器视图
mode: 'hash', // 模式
routes: [
{
path: '/',
name: 'home',
component: '<div>Home</div>',
beforeEnter: (next) => {
console.log('before enter home')
next()
},
afterEnter: (next) => {
console.log('enter home')
next()
},
beforeLeave: (next) => {
console.log('start leave home')
next()
}
},
{
path: '/bar',
name: 'bar',
component: '<div>Bar</div>',
beforeEnter: (next) => {
console.log('before enter bar')
next()
},
afterEnter: (next) => {
console.log('enter bar')
next()
},
beforeLeave: (next) => {
console.log('start leave bar')
next()
}
},
{
path: '/foo',
name: 'foo',
component: '<div>Foo</div>'
}
]
})
思路整理
首先是数据驱动,所以我们可以通过一个 route 对象来表述当前路由状态,比如:
current = {
path: '/', // 路径
query: {}, // query
params: {}, // params
name: '', // 路由名
fullPath: '/', // 完整路径
route: {} // 记录当前路由属性
}
current.route 内存放当前路由的配置信息,所以我们只需要监听 current.route 的变化来动态 render 页面便可。
接着我么需要监听不同的路由变化,做相应的处理。以及实现 hash 和history 模式。
据驱动
这里我们延用 vue 数据驱动模型,实现一个简单的数据劫持,并更新视图。首先定义我们的 observer
class Observer {
constructor (value) {
this.walk(value)
}
walk (obj) {
Object.keys(obj).forEach((key) => {
// 如果是对象,则递归调用walk,保证每个属性都可以被defineReactive
if (typeof obj[key] === 'object') {
this.walk(obj[key])
}
defineReactive(obj, key, obj[key])
})
}
}
function defineReactive(obj, key, value) {
let dep = new Dep()
Object.defineProperty(obj, key, {
get: () => {
if (Dep.target) {
// 依赖收集
dep.add()
}
return value
},
set: (newValue) => {
value = newValue
// 通知更新,对应的更新视图
dep.notify()
}
})
}
export function observer(value) {
return new Observer(value)
}
再接着,我们需要定义 Dep 和 Watcher:
export class Dep {
constructor () {
this.deppend = []
}
add () {
// 收集watcher
this.deppend.push(Dep.target)
}
notify () {
this.deppend.forEach((target) => {
// 调用watcher的更新函数
target.update()
})
}
}
Dep.target = null
export function setTarget (target) {
Dep.target = target
}
export function cleanTarget() {
Dep.target = null
}
// Watcher
export class Watcher {
constructor (vm, expression, callback) {
this.vm = vm
this.callbacks = []
this.expression = expression
this.callbacks.push(callback)
this.value = this.getVal()
}
getVal () {
setTarget(this)
// 触发 get 方法,完成对 watcher 的收集
let val = this.vm
this.expression.split('.').forEach((key) => {
val = val[key]
})
cleanTarget()
return val
}
// 更新动作
update () {
this.callbacks.forEach((cb) => {
cb()
})
}
}
到这里我们实现了一个简单的订阅-发布器,所以我们需要对 current.route做数据劫持。一旦current.route更新,我们可以及时的更新当前页面:
// 响应式数据劫持
observer(this.current)
// 对 current.route 对象进行依赖收集,变化时通过 render 来更新
new Watcher(this.current, 'route', this.render.bind(this))
恩....到这里,我们似乎已经完成了一个简单的响应式数据更新。其实 render 也就是动态的为页面指定区域渲染对应内容,这里只做一个简化版的 render:
render() {
let i
if ((i = this.history.current) && (i = i.route) && (i = i.component)) {
document.getElementById(this.container).innerHTML = i
}
}
hash 和 history
接下来是 hash 和history模式的实现,这里我们可以沿用 vue-router的思想,建立不同的处理模型便可。来看一下我实现的核心代码:
this.history = this.mode === 'history' ?
new HTML5History(this) :
new HashHistory(this)
当页面变化时,我们只需要监听 hashchange 和 popstate 事件,做路由转换 transitionTo:
/**
* 路由转换
* @param target 目标路径
* @param cb 成功后的回调
*/
transitionTo(target, cb) {
// 通过对比传入的 routes 获取匹配到的 targetRoute 对象
const targetRoute = match(target, this.router.routes)
this.confirmTransition(targetRoute, () => {
// 这里会触发视图更新
this.current.route = targetRoute
this.current.name = targetRoute.name
this.current.path = targetRoute.path
this.current.query = targetRoute.query || getQuery()
this.current.fullPath = getFullPath(this.current)
cb && cb()
})
}
/**
* 确认跳转
* @param route
* @param cb
*/
confirmTransition (route, cb) {
// 钩子函数执行队列
let queue = [].concat(
this.router.beforeEach,
this.current.route.beforeLeave,
route.beforeEnter,
route.afterEnter
)
// 通过 step 调度执行
let i = -1
const step = () => {
i ++
if (i > queue.length) {
cb()
} else if (queue[i]) {
queue[i](step)
} else {
step()
}
}
step(i)
}
}
这样我们一方面通过 this.current.route = targetRoute 达到了对之前劫持数据的更新,来达到视图更新。另一方面我们又通过任务队列的调度,实现了基本的钩子函数beforeEach、beforeLeave、beforeEnter、afterEnter。
到这里其实也就差不多了,接下来我们顺带着实现几个API吧:
/**
* 跳转,添加历史记录
* @param location
* @example this.push({name: 'home'})
* @example this.push('/')
*/
push (location) {
const targetRoute = match(location, this.router.routes)
this.transitionTo(targetRoute, () => {
changeUrl(this.router.base, this.current.fullPath)
})
}
/**
* 跳转,添加历史记录
* @param location
* @example this.replaceState({name: 'home'})
* @example this.replaceState('/')
*/
replaceState(location) {
const targetRoute = match(location, this.router.routes)
this.transitionTo(targetRoute, () => {
changeUrl(this.router.base, this.current.fullPath, true)
})
}
go (n) {
window.history.go(n)
}
function changeUrl(path, replace) {
const href = window.location.href
const i = href.indexOf('#')
const base = i >= 0 ? href.slice(0, i) : href
if (replace) {
window.history.replaceState({}, '', `${base}#/${path}`)
} else {
window.history.pushState({}, '', `${base}#/${path}`)
}
}
源码:https://link.zhihu.com/?target=https%3A//github.com/muwoo/blogs/tree/master/src/router
今天给到大家福利是《Vue.js源码全方位深入解析 (含Vue3.0源码分析)》,领取方式,转发+点赞,私信我 "源码", 即可免费获取。
相关推荐
- Vue3非兼容变更——函数式组件(vue 兼容)
-
在Vue2.X中,函数式组件有两个主要应用场景:作为性能优化,因为它们的初始化速度比有状态组件快得多;返回多个根节点。然而在Vue3.X中,有状态组件的性能已经提高到可以忽略不计的程度。此外,有状态组...
- 利用vue.js进行组件化开发,一学就会(一)
-
组件原理/组成组件(Component)扩展HTML元素,封装可重用的代码,核心目标是为了可重用性高,减少重复性的开发。组件预先定义好行为的ViewModel类。代码按照template\styl...
- Vue3 新趋势:10 个最强 X 操作!(vue.3)
-
Vue3为前端开发带来了诸多革新,它不仅提升了性能,还提供了...
- 总结 Vue3 组件管理 12 种高级写法,灵活使用才能提高效率
-
SFC单文件组件顾名思义,就是一个.vue文件只写一个组件...
- 前端流行框架Vue3教程:17. _组件数据传递
-
_组件数据传递我们之前讲解过了组件之间的数据传递,...
- 前端流行框架Vue3教程:14. 组件传递Props效验
-
组件传递Props效验Vue组件可以更细致地声明对传入的props的校验要求...
- 前端流行框架Vue3教程:25. 组件保持存活
-
25.组件保持存活当使用...
- 5 个被低估的 Vue3 实战技巧,让你的项目性能提升 300%?
-
前端圈最近都在卷性能优化和工程化,你还在用老一套的Vue3开发方法?作为摸爬滚打多年的老前端,今天就把私藏的几个Vue3实战技巧分享出来,帮你在开发效率、代码质量和项目性能上实现弯道超车!一、...
- 绝望!Vue3 组件频繁崩溃?7 个硬核技巧让性能暴涨 400%!
-
前端的兄弟姐妹们五一假期快乐,谁还没在Vue3项目上栽过跟头?满心欢喜写好的组件,一到实际场景就频频崩溃,页面加载慢得像蜗牛,操作卡顿到让人想砸电脑。用户疯狂吐槽,领导脸色难看,自己改代码改到怀疑...
- 前端流行框架Vue3教程:15. 组件事件
-
组件事件在组件的模板表达式中,可以直接使用...
- Vue3,看这篇就够了(vue3 从入门到实战)
-
一、前言最近很多技术网站,讨论的最多的无非就是Vue3了,大多数都是CompositionAPI和基于Proxy的原理分析。但是今天想着跟大家聊聊,Vue3对于一个低代码平台的前端更深层次意味着什么...
- 前端流行框架Vue3教程:24.动态组件
-
24.动态组件有些场景会需要在两个组件间来回切换,比如Tab界面...
- 前端流行框架Vue3教程:12. 组件的注册方式
-
组件的注册方式一个Vue组件在使用前需要先被“注册”,这样Vue才能在渲染模板时找到其对应的实现。组件注册有两种方式:全局注册和局部注册...
- 焦虑!Vue3 组件频繁假死?6 个奇招让页面流畅度狂飙 500%!
-
前端圈的朋友们,谁还没在Vue3项目上踩过性能的坑?满心期待开发出的组件,一到高并发场景就频繁假死,用户反馈页面点不动,产品经理追着问进度,自己调试到心态炸裂!别以为这是个例,不少人在电商大促、数...
- 前端流行框架Vue3教程:26. 异步组件
-
根据上节课的代码,我们在切换到B组件的时候,发现并没有网络请求:异步组件:...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)