手把手教你写VueRouter

Vue-Router提供了俩个组件 `router-link` `router-view`, 提供了俩个原型上的属性`$route` `$router` ,我现在跟着源码来把它实现一下
开始
先看平时使用的 `Vue-Router` ,引入`Router` , `Vue.use` 注册插件。直接从这里开始入手
使用场景
import Vue from 'vue'
import Router from "../vue-router"
import routes from './routes'
Vue.use(Router)
let router = new Router({
routes
})
index
先看`vue-router.js`文件,先生成一个`VueRouter`类,然后导入`install`方法,因为`Vue-Router`的`install`方法比`Vuex`复杂一些,所以将`install`单独作为一个文件。
import install from './install';
class VueRouter {
constructor(options) {
}
}
VueRouter.install = install;
export default VueRouter
Vue.use()
来先看 `Vue.use()`的源码中的一部分,这里面判断注册的插件里的`install`是不是一个函数,有就执行插件里的`install`函数。或者判断插件本身是不是一个函数,有就执行插件本身。这里本质上是没有区别,有没有`install`都可以。而`VueRouter`使用了`install`,目的是为了将`install`作为入口函数,方便封装,同时也将`install`和其他代码分开。
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
install
上述已经将`vue-router`的类构建好,现在`VueRouter`实例已经有了,然后执行`vue.use()`,然后会执行`VueRouter`类里的`install`函数,那来看`install.js`。
install里使用了`Vue.mixin`,混入代码,下面代码是在当前组件生命周期`beforeCreate`里混入代码,代码逻辑是判断当前组件是否为根组件,如果是则将`_routerRoot`作为键放入当前组件中,值为`Vue`实例。再将`_router`作为键放入当前组件中,值为`VueRouter`实例。然后执行初始化操作。
如果不为当前组件不是根组件,则该组件为根组件的子组件。将`_routerRoot`作为键放入当前组件中,值为父组件的`_routerRoot`,从父亲身上获取.
`$route`和`$router`是利用`Object.definePropert`代理`_routerRoot`里的`_router`和`_route`,访问到的。
接着注册全局组件`router-view`和`router-link`
import RouterView from '../components/router-view'
import RouterLink from '../components/router-link' const install = (_Vue, s) => {
_Vue.mixin({
beforeCreate() {
if (this.$options.router) { // 判断是不是根组件
this._routerRoot = this; // 把vue实例放在当前组件的——routerRoot属性上
this._router = this.$options.router // 这里直接获取根实例
this._router.init(this); // 初始化
_Vue.util.defineReactive(this, '_route', this._router.history.current) // 将属性_route成为响应式属性
} else {
this._routerRoot = this.$parent && this.$parent._routerRoot // 这里的是从父亲最顶层获取Router实例
}
}
})
Object.defineProperty(_Vue.prototype, '$route', { // 代理$route
get() {
return this._routerRoot._route
}
})
Object.defineProperty(_Vue.prototype, '$router', { // 代理$router
get() {
return this._routerRoot._router
}
})
_Vue.component('router-view', RouterView) // 注册组件router-view
_Vue.component('router-link', RouterLink) // 注册组件router-view
}
export default install
init
vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。
然后回到`VueRouter`类中,此时多了个`init`函数。目前做的路由方式是`hash`方式,还有另外俩种方式,`history`,`abstract`。因为有三种方式,所以`Vue-Router`做了一个父类`base`执行同样的逻辑,子类三种方式继承父类`base`,再独自执行自己方式的代码。
通过`new HashHistory` 获取 `history`实例,初始化`init`执行`history`实例对应函数。将目光放到`history`实例上,这些函数来自于`base.js`和`hash.js`。
import install from './install';
class VueRouter {
constructor(options) {
this.history = new HashHistory(this);
}
init(app) {
const history = this.history;
const setupHashLister = () => {
history.setupLister(); // hash的跳转
}
history.transitionTo(
history.getCurrentLocation(),
setupHashLister
)
history.listen((route) => {
app._route = route
})
}
}
VueRouter.install = install;
export default VueRouter
base.js
先看构造函数`construcror`,将`router`作为键放在自身实例上,值为`VueRouter`实例,`curent`为当前导航正要离开的路由,也就是路由守卫的参数里的`from`<br/>
1.`transitionTo()`为跳转后立即执行的函数,传入当前路径和回调函数,`r`为`$route`,是扁平化后的配置,也就是即将要进入的目标 路由对象<br/>
2.`cb`是`History`的`listen()`函数,将`$route`放入当前组件上供用户使用。<br/>
3.`callback`是执行`HashHistory`的`setupHashLister()`函数,是给当前`window`添加监听事件`onhashChange`,`onhashChange`后续通过`hash`变化执行`transitionTo`进行更新。<br/>
4.最后将`r`赋值给`current`,更新路由信息。
class History {
constructor(router) {
this.router = router;
this.current = createRoute(null, {
path: '/'
})
}
transitionTo(location, callback) {
let r = this.router.match(location)
if (location == this.current.path && r.matched.length == this.current.matched.length) { // 防止重复跳转
return
}
this.cb && this.cb(r);
callback && callback();
this.current = r;
}
listen(cb) {
this.cb = cb;
}
}
hash.js
`hash`方式的函数就简单介绍一下,看构造函数`constructor`,跟父类一样赋值`router`。执行`ensureSlash`函数,因为`hash`相比其他函数,一进入页面就会多个#。所以就初始化的时候处理一下。`getCurrentLocation`函数是获取当前路径的,`push`是`hash`方式的跳转,`setupLister`函数是刚刚所述的监听函数`hashchange`。
import Histroy from './base';
function ensureSlash() {
if (window.location.hash) {
return
}
window.location.hash = '/';
}
class HashHistory extends Histroy {
constructor(router) {
super();
this.router = router;
ensureSlash();
}
getCurrentLocation() {
return window.location.hash.slice(1);
}
push(location){
this.transitionTo(location,()=>{
window.location.hash = location
})
}
setupLister() {
window.addEventListener('hashchange', () => {
this.transitionTo(window.location.hash.slice(1));
})
}
}
export default HashHistory
扁平化
刚刚`base.js`里执行的`this.router.match(location)`以及`createRoute()`,都是需要建立在扁平化配置基础之上的。
平时配置的路由是这样的,需要将配置进行扁平化,才能用得上。
[
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: About,
children: [
{
path: 'add',
name: 'add',
component: Add
},
{
path: 'bull',
name: 'bull',
component: Bull
}
]
}
]
扁平化后是这样的
/: {path: "/", component: {…}, parnent: undefined}
/about: {path: "about", component: {…}, parnent: {…}}
/about/add: {path: "add", component: {…}, parnent: {…}}
/about/bull: {path: "bull", component: {…}, parnent: {…}}
接着看扁平化函数createMatcher以及createRouteMap
createMatcher
`createMatcher`返回一个`match`函数,`match`方法是匹配路径,根据路径拿扁平化对象里的配置,然后执行`createRoute`方法,将其转化为`route`,返回。`pathMap`由`createRouteMap`生成
import createRouteMap from './create-route-map'
import { createRoute } from './history/base'; export default function createMatcher(routes) {
let { pathList, pathMap } = createRouteMap(routes); function match(location) {
console.log(pathMap)
let record = pathMap[location]; return createRoute(record,{
path: location
})
} return {
match
}
}
createRouteMap
将`routes`配置传入`createRouteMap`中,遍历`routes`,进行扁平化操作
`pathMap`以路径为键名,值为一个对象包裹着路径,组件,父组件。
将路径匹配上父组件的路径和自身的路径
如果有子组件就进行递归,全部转为扁平化返回。
export default function createRouteMap(routes, oldPathList, oldpathMap) {
let pathList = oldPathList || [];
let pathMap = oldpathMap || Object.create(null);
routes.forEach(route => {
addRouteRecord(route, pathList, pathMap);
})
return {
pathList,
pathMap
}
}
function addRouteRecord(route, pathList, pathMap,parnent) {
let path = parnent ? `${parnent.path}/${route.path}`: route.path;
let record = {
path: route.path,
component: route.component,
parnent
}
if (!pathMap[path]) {
pathList.push(path);
pathMap[path] = record;
}
if(route.children){
route.children.forEach(route=>{
addRouteRecord(route, pathList, pathMap,record)
})
}
}
createRoute
`createRoute`是生成`$route`的函数,传入参数为扁平化配置,路径。将`res`作为空数组,如果传进来的扁平化配置有值,则进行`while`循环,将自己从数组头部插入,取出父组件再从头部插入,如此反复,得到一个含着层次关系的数组。将`loaction`和数组包裹为对象返回。
export function createRoute(record, location) {
let res = [];
if (record) {
while (record) {
res.unshift(record)
record = record.parnent
}
}
return {
...location,
matched: res
}
}
router-view
然后在来看看`routerview`
是一个函数式组件,
返回`render`方法
进行`while`循环,遍历出嵌套的`routerview`
用`depth`作为深度,也是`matched`的`index`.
每遍历一次,就在`$vnode.data.rouView` 改为`true`,将深度加1
返回对应的组件即可
export default {
name:'routerView',
functional: true,
render(h,{parent,data}) {
let route = parent.$route
let depth = 0;
while (parent) {
if (parent.$vnode && parent.$vnode.data.routeView) {
depth++;
}
parent = parent.$parent;
}
data.routeView = true;
let record = route.matched[depth];
if (!record) {
return h();
}
return h(record.component, data);
}
}
router-link
再来看看`routerlink`
没什么东西就返回一个`a`标签,用插槽把对应的文本显示出来,在添加的跳转事件
调用`$router`的`push`方法,也就是`Router`类上的`push`
export default {
name: 'routerLink',
props: {
to: {
type: String,
required: true
},
tag: {
type: String,
default: 'a'
}
},
methods: {
handler(to) {
this.$router.push(to) // 路由跳转
}
},
render() {
return <a onClick={this.handler.bind(this,this.to)}>{this.$slots.default[0].text}</a>
}
}
vuerouter草稿:https://juejin.im/post/6862215979745673224
手把手教你写VueRouter的更多相关文章
- 手把手教你写Sublime中的Snippet
手把手教你写Sublime中的Snippet Sublime Text号称最性感的编辑器, 并且越来越多人使用, 美观, 高效 关于如何使用Sublime text可以参考我的另一篇文章, 相信你会喜 ...
- 手把手教你写LKM rookit! 之 第一个lkm程序及模块隐藏(一)
唉,一开始在纠结起个什么名字,感觉名字常常的很装逼,于是起了个这<手把手教你写LKM rookit> 我觉得: 你们觉得:...... 开始之前,我们先来理解一句话:一切的操作都是系统调用 ...
- 手把手教你写电商爬虫-第三课 实战尚妆网AJAX请求处理和内容提取
版权声明:本文为博主原创文章,未经博主允许不得转载. 系列教程: 手把手教你写电商爬虫-第一课 找个软柿子捏捏 手把手教你写电商爬虫-第二课 实战尚妆网分页商品采集爬虫 看完两篇,相信大家已经从开始的 ...
- 手把手教你写电商爬虫-第四课 淘宝网商品爬虫自动JS渲染
版权声明:本文为博主原创文章,未经博主允许不得转载. 系列教程: 手把手教你写电商爬虫-第一课 找个软柿子捏捏 手把手教你写电商爬虫-第二课 实战尚妆网分页商品采集爬虫 手把手教你写电商爬虫-第三课 ...
- 只有20行Javascript代码!手把手教你写一个页面模板引擎
http://www.toobug.net/article/how_to_design_front_end_template_engine.html http://barretlee.com/webs ...
- [原创]手把手教你写网络爬虫(4):Scrapy入门
手把手教你写网络爬虫(4) 作者:拓海 摘要:从零开始写爬虫,初学者的速成指南! 封面: 上期我们理性的分析了为什么要学习Scrapy,理由只有一个,那就是免费,一分钱都不用花! 咦?怎么有人扔西红柿 ...
- [原创]手把手教你写网络爬虫(5):PhantomJS实战
手把手教你写网络爬虫(5) 作者:拓海 摘要:从零开始写爬虫,初学者的速成指南! 封面: 大家好!从今天开始,我要与大家一起打造一个属于我们自己的分布式爬虫平台,同时也会对涉及到的技术进行详细介绍.大 ...
- [原创]手把手教你写网络爬虫(7):URL去重
手把手教你写网络爬虫(7) 作者:拓海 摘要:从零开始写爬虫,初学者的速成指南! 封面: 本期我们来聊聊URL去重那些事儿.以前我们曾使用Python的字典来保存抓取过的URL,目的是将重复抓取的UR ...
- Android开发之手把手教你写ButterKnife框架(三)
欢迎转载,转载请标明出处: http://blog.csdn.net/johnny901114/article/details/52672188 本文出自:[余志强的博客] 一.概述 上一篇博客讲了, ...
随机推荐
- idea中maven导入依赖报红的解决办法
使用idea创建maven项目,maven导入依赖报红,从以下几个步骤排查解决问题: 1.首先查看maven的安装和配置有没有问题.那么,要看那些内容呢.maven的安装位置.maven的settin ...
- 题解 SP1812 【LCS2 - Longest Common Substring II 】
对于本题这样的多字符串的子串匹配问题,其实用广义后缀自动机就可以很好的解决,感觉会比普通的后缀自动机做法方便一些. 首先记录出每个节点被多少个字符串更新,也就是记录每个节点有多少个字符串能到达它,可以 ...
- LeetCode 85 | 如何从矩阵当中找到数字围成的最大矩形的面积?
本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是LeetCode专题53篇文章,我们一起来看看LeetCode中的85题,Maximal Rectangle(最大面积矩形). 今天的 ...
- AI面试之SVM推导
SVM现在主流的有两个方法.一个是传统的推导,计算支持向量求解的方法,一个是近几年兴起的梯度下降的方法. 梯度下降方法的核心是使用了hinge loss作为损失函数,所以最近也有人提出的深度SVM其实 ...
- Windows电脑多个SSH Key管理.md
笔者偏在阿里云,Github,开源中国上均存放一些私有项目代码,因此需要再Windows电脑上配置多个SSH Key 环境 操作系统:windows 7 Git 提示:Git 安装后就可以使用 Git ...
- Eclipse普通java Project文件路径问题
Eclipse普通java Project文件路径问题 项目的结构如图 读取src里某个包下的文件,代码如下 BufferedReader br=new BufferedReader(new File ...
- expect正则捕获返回结果
expect正则捕获返回结果 expect: expect -re "([0-9]*)([a-zA-Z]*)"send_user "num is $expect_out( ...
- Python删除元组
Python删除元组: 删除元组中的某一个元素: # 删除元组中的元素 tuple_1 = ('a','b','c','d','e') # 删除第 2 个元素 tuple_1 = tuple_1[:1 ...
- 11-19 configparser模块
该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值). 创建文件 import configparser config = ...
- AJAX 是什么?
AJAX 简介 AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术. AJAX 是什么? AJAX = Asynchronous JavaScript and XML. AJAX ...