本文详细解析如何使用原生JavaScript从零封装Vue-Router。内容涵盖Hash与History两种路由模式的区别与兼容实现,深入讲解push、replace、go等导航方法的底层逻辑,以及通过next回调函数实现beforeEach路由拦截器的完整流程。同时包含router-link与router-view组件的封装思路,帮助开发者理解前端路由的核心机制。
摘要
近期对Vue-router的部分核心方法原理进行了复现与整理。相较于之前实现的axios,本次实现的路由模块逻辑更为复杂,涉及更多状态管理与事件监听机制。
本次实现主要涵盖push、go、replace等导航方法,以及beforeEach和afterNext等关键钩子函数的处理逻辑。
实现的核心原理包括对URL变化的响应机制,以及router-view和router-link组件的渲染逻辑。
1.hash和history
在开始编码前,需明确hash模式与history模式的区别,主要差异体现在URL格式及浏览器行为上。
hash模式下,路由更改不会触发页面重新请求,且URL中路由路径前带有#符号。
history模式下,URL中不包含#号,且修改URL会触发浏览器的重新请求行为。
无论采用何种实现方式,代码均需兼容上述两种模式,以确保通用性。
Vue-router在创建实例时允许配置mode参数,以指定使用hash还是history模式。
因此,我们的Router类在初始化时需接收并处理该模式配置:
function myrouter (obj) {
this.mode = obj.mode || 'hash'
}
2.push go replace方法
由于router-view尚未实现,页面演示阶段暂时使用h1标签模拟当前路由内容的展示。
(1) push
对于hash模式,直接修改URL的hash值即可实现路由跳转。
在history模式下,则需调用pushState方法更新历史记录。
myrouter.prototype.push = function (data) {
//判断路由模式
if (this.mode == 'hash') {
location.href = orgin + '/#' + ifObj(data);
h1.innerHTML = ifObj(data)
}
else if (this.mode = 'history') {
history.pushState({}, '', orgin + ifObj(data))
h1.innerHTML = ifObj(data)
}
}
ifObj是用于判断参数类型的辅助方法:
//判断参数类型
function ifObj (data) {
if (typeof data == 'object') {
return data.path
} else {
return data;
}
}
(2) go
go方法的实现相对简单,直接调用浏览器原生的history.go方法即可:
myrouter.prototype.go = function (num) {
history.go(num)
}
(3) replace
对于replace方法,在不同模式下需调用不同的API。
在hash模式下,需要调用location.replace()方法。
在history模式下,则需要调用history.replaceState()方法。
myrouter.prototype.replace = function (data) {
let orgin = location.origin;
//判断路由模式
if (this.mode == 'hash') {
//判断是否使用路由拦截
location.replace(orgin + '/#' + ifObj(data));
h1.innerHTML = ifObj(data)
} else if (this.mode == 'history') {
history.replaceState({}, '', orgin + ifObj(data))
h1.innerHTML = ifObj(data)
}
}至此,这三个导航方法已具备基本功能,但后续还需结合路由拦截逻辑进行增强,包括对push、replace、go方法的改造。
3.监听方法
仅实现导航方法是不够的,若用户直接在地址栏修改URL,页面需做出响应,因此必须监听URL变化。
浏览器原生提供了一些监听URL变化的事件:
对于hash模式,可以使用onhashchange事件监听hash值的变化。
对于history模式,可以使用onpopstate事件监听前进或后退操作。
myrouter.prototype.update = function () {
let _this = this;
//判断路由模式
if (this.mode == 'hash') {
//监听url哈希值的变化
window.onhashchange = function () {
h1.innerHTML = location.hash.replace('#/', '')
}
}
else if (this.mode == 'history') {
//监听history模式下前进后退的操作
window.addEventListener('popstate', function () {
h1.innerHTML = location.pathname
});
window.onload = function () {
h1.innerHTML = location.pathname
}
}
}
此外,onload事件主要用于处理history模式下页面刷新导致的状态丢失问题,通过监听load事件来同步当前路径。
4.beforeEach钩子函数
我们知道,beforeEach钩子函数接收一个回调函数作为参数,因此源码中需要保存该回调函数:
myrouter.prototype.beforeEach = function (config) {
this.saveBefore = config;
}
该回调函数接收三个参数,因此构造函数需进行相应调整:
function myrouter (obj) {
this.mode = obj.mode || 'hash'
this.saveBefore = null
this.saveAfter = null
this.from = ''
this.to = ''
}
无论执行何种导航方法(push、replace、go)或监听事件,都需实时更新to和from的值。
钩子回调函数的第三个参数是一个next回调函数(逻辑较为复杂)。
重点在于next回调函数的处理,next方法支持三种参数传递方式:
true / false :表示继续执行或停止执行。
string :表示跳转到指定路由。
空参数 :表示停止执行(或不调用next)。
因此,在next方法中:
需对参数类型进行判断,并根据hash和history不同模式执行相应的跳转逻辑:
myrouter.prototype.next = function () {
//当next中没有参数
if (arguments[0] == undefined) {
//判断路由模式
if (this.mode == 'hash') {
let str = location.origin + '/#' + this.to
//判断是什么方法
if (this.methodType == 'replace') {
location.replace(str)
} else if (this.methodType == 'push') {
location.href = str
}
h1.innerHTML = str;
} else if (this.mode = 'history') {
let str = location.origin + this.to
if (this.methodType == 'push') {
history.pushState({}, '', str)
} else if (this.methodType == 'replace') {
history.replaceState({}, '', str)
}
h1.innerHTML = str;
}
this.from = this.to
}
//当next中参数是某个路径
else if (typeof arguments[0] == 'string') {
//判断路由模式
if (this.mode == 'hash') {
location.hash = arguments[0]
} else if (this.mode = 'history') {
let str = location.origin + arguments[0]
//判断是什么方法
if (this.methodType == 'push') {
history.pushState({}, '', str)
} else if (this.methodType == 'replace') {
history.replaceState({}, '', str)
}
h1.innerHTML = str;
}
this.to = arguments[0]
}
//当next里面传入其他参数(false)或者没有使用next方法
else {
if (this.mode == 'hash') {
location.hash = this.from
} else if (this.mode = 'history') {
if (this.from) {
let str = location.origin + this.from
if (this.methodType == 'push') {
history.pushState({}, '', str)
} else if (this.methodType == 'replace') {
history.replaceState({}, '', str)
}
} else {
history.back()
}
}
this.to = this.from
}
}next方法编写完成后,只需在push、replace、go及监听方法中判断this.saveBefore是否为空,若不为空则调用该方法执行路由拦截。
5.router-link
实现router-link相对简单,可直接封装为一个子组件,并在main.js中引入使用。
主要涉及父组件向子组件传值的问题:
此处直接展示相关代码:
<template>
<a @click="fn" class="routerlink">
<slot></slot>
</a>
</template>
<script>
import router from '../myrouter'
export default {
name : 'routerLink',
props : ['to','replace'],
data(){
return {
title : 'router-link'
}
},
created(){
},
methods : {
fn(){
if(this.to){
this.$myrouter.push(this.to);
}else if(this.replace){
this.$myrouter.replace(this.replace)
}
}
}
}
</script>
<style scoped>
.routerlink{
cursor:pointer
}
</style>6.router-view
router-view的实现需考虑更多细节,可封装为子组件,并将之前的h1标签替换为该子组件。
<template>
<div class="routerview"></div>
</template>
但这种方式无法实现嵌套路由。
因此,我们的解决策略是:
对path和routers进行匹配,记录匹配值的层级,并对对应层级的router-view进行渲染。
。。。。md说不明白。
emmm,这就要靠自己理解了。。。。
鉴于上述方法及原理涉及大量代码,且粘贴过程中可能存在删减导致的问题,最后直接附上完整源码。
7.myrouter.js代码
import Vue from 'vue'
var routerview = document.getElementsByClassName('routerview')
function myrouter (obj) {
this.mode = obj.mode || 'hash'
this.saveBefore = null
this.saveAfter = null
this.from = ''
this.to = ''
this.methodType = ''
this.routes = obj.routes;
}
myrouter.prototype.push = function (data) {
this.methodType = 'push'
let orgin = location.origin;
//判断路由模式
if (this.mode == 'hash') {
this.to = ifObj(data)
this.from = location.hash.replace('#', '');
//判断是否使用路由拦截
if (this.saveAfter) {
this.saveAfter(this.to, this.from);
}
if (this.saveBefore) {
this.saveBefore(this.to, this.from, this.next)
} else {
location.href = orgin + '/#' + ifObj(data);
h1.innerHTML = returnView(ifObj(data), this.routes)
}
}
else if (this.mode = 'history') {
this.to = ifObj(data)
this.from = location.pathname;
if (this.saveAfter) {
this.saveAfter(this.to, this.from);
}
if (this.saveBefore) {
this.saveBefore(this.to, this.from, this.next)
} else {
history.pushState({}, '', orgin + ifObj(data))
routerview.innerHTML = ''
routerview.appendChild(returnView(ifObj(data).replace('/', ''), this.routes))
}
}
}
myrouter.prototype.go = function (num) {
this.methodType = 'go'
history.go(num)
}
myrouter.prototype.replace = function (data) {
this.methodType = 'replace'
let orgin = location.origin;
//判断路由模式
if (this.mode == 'hash') {
//判断是否使用路由拦截
if (this.saveAfter) {
this.saveAfter(this.to, this.from);
}
if (this.saveBefore) {
this.to = ifObj(data)
this.from = location.hash.replace('#', '')
this.saveBefore(this.to, this.from, this.next)
} else {
location.replace(orgin + '/#' + ifObj(data));
routerview.innerHTML = ''
routerview.appendChild(ifObj(data).replace('/', ''))
}
} else if (this.mode == 'history') {
if (this.saveAfter) {
this.saveAfter(this.to, this.from);
}
if (this.saveBefore) {
this.to = ifObj(data)
this.from = location.pathname;
this.saveBefore(this.to, this.from, this.next)
} else {
history.replaceState({}, '', orgin + ifObj(data))
routerview.innerHTML = ''
routerview.appendChild(ifObj(data).replace('/', ''))
}
}
}
//钩子的next回调函数
myrouter.prototype.next = function () {
//当next中没有参数
if (arguments[0] == undefined) {
//判断路由模式
if (this.mode == 'hash') {
let str = location.origin + '/#' + this.to
//判断是什么方法
if (this.methodType == 'replace') {
location.replace(str)
} else if (this.methodType == 'push') {
location.href = str
}
let arr = this.to.split('/');
let path = '/' + arr[arr.length - 1]
let com = (ifChild(this.to, this.routes))
// let path = ('/' + location.hash.replace('#', '').split('/').pop());
// let com = (ifChild(location.hash.replace('#', ''), this.routes))
routerview[routerview.length - 1].innerHTML = ''
routerview[routerview.length - 1].appendChild(returnView(path, com))
} else if (this.mode = 'history') {
let str = location.origin + this.to
if (this.methodType == 'push') {
history.pushState({}, '', str)
} else if (this.methodType == 'replace') {
history.replaceState({}, '', str)
}
routerview.innerHTML = ''
routerview.appendChild(returnView(location.pathname, this.routes))
}
this.from = this.to
}
//当next中参数是某个路径
else if (typeof arguments[0] == 'string') {
//判断路由模式
if (this.mode == 'hash') {
location.hash = arguments[0]
} else if (this.mode = 'history') {
let str = location.origin + arguments[0]
//判断是什么方法
if (this.methodType == 'push') {
history.pushState({}, '', str)
} else if (this.methodType == 'replace') {
history.replaceState({}, '', str)
}
routerview.innerHTML = ''
routerview.appendChild(returnView(location.pathname, this.routes))
}
this.to = arguments[0]
}
//当next里面传入其他参数(false)或者没有使用next方法
else {
if (this.mode == 'hash') {
location.hash = this.from
} else if (this.mode = 'history') {
if (this.from) {
let str = location.origin + this.from
if (this.methodType == 'push') {
history.pushState({}, '', str)
} else if (this.methodType == 'replace') {
history.replaceState({}, '', str)
}
} else {
history.back()
}
}
this.to = this.from
}
}
//前置钩子函数(主要用于保存回调函数)
myrouter.prototype.beforeEach = function (config) {
this.saveBefore = config;
}
//后置钩子函数
myrouter.prototype.afterEach = function (config) {
this.saveAfter = config
}
//挂在在window上的监听方法
myrouter.prototype.update = function () {
let _this = this;
//判断路由模式
if (this.mode == 'hash') {
//监听url哈希值的变化
window.onhashchange = function () {
//判断是否使用路由拦截
if (_this.saveAfter) {
_this.saveAfter(_this.to, _this.from);
}
let length = location.hash.replace('#', '').split('/').length - 1;
if (routerview[length]) {
routerview[length].remove()
}
if (_this.saveBefore) {
_this.to = location.hash.replace('#', '')
_this.saveBefore(_this.to, _this.from, _this.next)
} else {
routerview.innerHTML = ''
routerview.appendChild(returnView(location.hash.replace('#/', ''), this.routes))
}
}
window.onload = function () {
if (location.hash.length == 0) {
location.href = location.origin + '/#' + location.pathname
}
if (_this.saveAfter) {
_this.saveAfter(_this.to, _this.from)
}
let arr = location.hash.replace('#', '').split('/');
arr.shift()
let too = ''
arr.forEach(val => {
if (_this.saveBefore) {
too += ('/' + val)
_this.to = too
_this.saveBefore(_this.to, _this.from, _this.next)
} else {
routerview.innerHTML = ''
routerview.appendChild(returnView(location.hash.replace('#/', ''), this.routes))
}
})
}
}
else if (this.mode == 'history') {
//监听history模式下前进后退的操作
window.addEventListener('popstate', function () {
_this.methodType = 'go'
//判断是否使用路由拦截
if (_this.saveAfter) {
_this.saveAfter(_this.to, _this.from);
}
if (_this.saveBefore) {
_this.to = location.pathname
_this.saveBefore(_this.to, _this.from, _this.next)
} else {
routerview.innerHTML = ''
routerview.appendChild(returnView(location.pathname, this, routes))
}
});
window.onload = function () {
if (location.hash.length != 0) {
location.href = location.href.replace('/#', '')
}
if (_this.saveAfter) {
_this.saveAfter(_this.to, _this.from);
}
if (_this.saveBefore) {
_this.to = location.pathname
_this.saveBefore(_this.to, _this.from, _this.next)
} else {
routerview.innerHTML = ''
routerview.appendChild(returnView(location.pathname, this.routes))
}
}
}
}
//判断参数类型
function ifObj (data) {
if (typeof data == 'object') {
return data.path
} else {
return data;
}
}
//通过路径path返回dom实例的方法
function returnView (path, routes) {
// debugger
if (path && routes) {
for (var i = 0; i < routes.length; i++) {
if (routes[i].path == path) {
if (typeof routes[i].component.template == 'string') {
let div = document.createElement('div');
div.innerHTML = routes[i].component.template
return div
} else {
return toDom(routes[i].component)
}
}
}
}
var div = document.createElement('div');
div.innerHTML = '<h1>404</h1>'
return div
}
function ifChild (path, routes) {
let arr = path.replace('/', '').split('/');
return returnChild(arr, routes);
}
function returnChild (arr, routes) {
if (arr && routes) {
if (arr.length == 1) {
for (var i = 0; i < routes.length; i++) {
if (arr[0] == routes[i].path.replace('/', '')) {
return routes
}
}
} else {
for (var i = 0; i < routes.length; i++) {
if (arr[0] == routes[i].path.replace('/', '')) {
arr.shift();
return returnChild(arr, routes[i].children)
}
}
}
}
}
//将vue组建转换成dom的方法
function toDom (view) {
const Instance = new Vue({
render (h) {
return h(view);
}
});
const component = Instance.$mount();
return component.$el
}
export default myrouter8.main.js代码
import Vue from 'vue'
import App from './App.vue'
// import router from './router'
import myrouter from '../router/myrouter'
import view1 from '../router/view/view1.vue'
import view2 from '../router/view/view2.vue'
import child2 from '../router/view/child2.vue'
const a = { template: '<h1>a页面</h1>' }
const b = { template: '<h1>b页面</h1>' }
const child1 = { template: '<h1>child1页面</h1>' }
const routes = [
{
path: '/a', component: view2, children: [
{ path: '/achild1', component: child1 },
{ path: '/achild2', component: child2 }
]
},
{ path: '/b', component: b },
{ path: '/c', component: view1 }
]
let router = new myrouter({
mode: 'hash',
routes: routes
})
router.beforeEach((to, from, next) => {
// console.log(to, from);
if (to == '/a') {
router.next()
} else if (to == '/b') {
router.next()
} else if (to == '/c') {
router.next()
} else if (to == '/d') {
router.next()
} else {
router.next()
}
})
router.afterEach((to, from) => {
if (to == '/a' && from == '/b') {
console.log('from b to a');
}
})
Vue.prototype.$myrouter = router;
new Vue({
el: '#app',
render: h => h(App),
// router,
})到此这篇关于JavaScript封装Vue-Router实现流程详解的文章就介绍到这了,更多相关JS封装Vue-Router内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!