您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

vue-router源码实例详解

2024/2/21 15:03:26发布21次查看
本文主要和大家分享vue-router源码阅读学习,如同分析vuex源码我们首先通过一个简单例子进行了解vue-router是如何使用的,然后在分析在源码中是如何实现的,希望能帮助到大家。
示例下面示例来自于example/basica/app.js
           import vue from 'vue' import vuerouter from 'vue-router' vue.use(vuerouter) const home = { template: '<div>home</div>' } const foo = { template: '<div>foo</div>' } const bar = { template: '<div>bar</div>' } const router = new vuerouter({ mode: 'history', base: __dirname, routes: [ { path: '/', component: home }, { path: '/foo', component: foo }, { path: '/bar', component: bar } ] }) new vue({ router, template: ` <div id="app"> <h1>basic</h1> <ul> <li><router-link to="/">/</router-link></li> <li><router-link to="/foo">/foo</router-link></li> <li><router-link to="/bar">/bar</router-link></li> <router-link tag="li" to="/bar" :event="['mousedown', 'touchstart']"> <a>/bar</a> </router-link> </ul> <router-view class="view"></router-view> </div> ` }).$mount('#app')
首先调用vue.use(vuerouter),vue.use()方法是vue用来进行插件安装的方法,这里主要用来安装vuerouter。然后实例化了vuerouter,我们来看看vuerouter这个构造函数到底做了什么。
从源码入口文件src/index.js开始看
import type { matcher } from './create-matcher'export default class vuerouter { constructor (options: routeroptions = {}) { this.app = null this.apps = [] this.options = options this.beforehooks = [] this.resolvehooks = [] this.afterhooks = [] this.matcher = creatematcher(options.routes || [], this) let mode = options.mode || 'hash' this.fallback = mode === 'history' && !supportspushstate && options.fallback !== false if (this.fallback) { mode = 'hash' } if (!inbrowser) { mode = 'abstract' } this.mode = mode switch (mode) { case 'history': this.history = new html5history(this, options.base) break case 'hash': this.history = new hashhistory(this, options.base, this.fallback) break case 'abstract': this.history = new abstracthistory(this, options.base) break default: if (process.env.node_env !== 'production') { assert(false, `invalid mode: ${mode}`) } } } init (app: any /* vue component instance */) { this.apps.push(app) // main app already initialized. if (this.app) { return } this.app = app const history = this.history if (history instanceof html5history) { history.transitionto(history.getcurrentlocation()) } else if (history instanceof hashhistory) { const setuphashlistener = () => { history.setuplisteners() } history.transitionto( history.getcurrentlocation(), setuphashlistener, setuphashlistener ) } history.listen(route => { this.apps.foreach((app) => { app._route = route }) }) } getmatchedcomponents (to?: rawlocation | route): array<any> { const route: any = to ? to.matched ? to : this.resolve(to).route : this.currentroute if (!route) { return [] } return [].concat.apply([], route.matched.map(m => { return object.keys(m.components).map(key => { return m.components[key] }) })) } }
代码一步步看,先从constructor函数的实现,首先进行初始化我们来看看这些初始化条件分别代表的是什么
this.app表示当前vue实例
this.apps表示所有app组件
this.options表示传入的vuerouter的选项
this.resolvehooks表示resolve钩子回调函数的数组,resolve用于解析目标位置
this.matcher创建匹配函数
代码中有creatematcher()函数,来看看他的实现
function creatematcher ( routes, router ) { var ref = createroutemap(routes); var pathlist = ref.pathlist; var pathmap = ref.pathmap; var namemap = ref.namemap; function addroutes (routes) { createroutemap(routes, pathlist, pathmap, namemap); } function match ( raw, currentroute, redirectedfrom ) { var location = normalizelocation(raw, currentroute, false, router); var name = location.name; // 命名路由处理 if (name) { // namemap[name]的路由记录 var record = namemap[name]; ... location.path = fillparams(record.path, location.params, ("named route \"" + name + "\"")); // _createroute用于创建路由 return _createroute(record, location, redirectedfrom) } else if (location.path) { // 普通路由处理 } // no match return _createroute(null, location) } return { match: match, addroutes: addroutes } }
creatematcher()有两个参数routes表示创建vuerouter传入的routes配置信息,router表示vuerouter实例。creatematcher()的作用就是传入的routes通过createroutemap创建对应的map,和一个创建map的方法。
我们先来看看createroutemap()方法的定义
function createroutemap ( routes, oldpathlist, oldpathmap, oldnamemap) { // 用于控制匹配优先级 var pathlist = oldpathlist || []; // name 路由 map var pathmap = oldpathmap || object.create(null); // name 路由 map var namemap = oldnamemap || object.create(null); // 遍历路由配置对象增加路由记录 routes.foreach(function (route) { addrouterecord(pathlist, pathmap, namemap, route); }); // 确保通配符总是在pathlist的最后,保证最后匹配 for (var i = 0, l = pathlist.length; i < l; i++) { if (pathlist[i] === '*') { pathlist.push(pathlist.splice(i, 1)[0]); l--; i--; } } return { pathlist: pathlist, pathmap: pathmap, namemap: namemap } }
createroutemap()有4个参数:routes代表的配置信息,oldpathlist包含所有路径的数组用于匹配优先级,oldnamemap表示name map,oldpathmap表示path map。createroutemap就是更新pathlist,namemap和pathmap。namemap到底代表的是什么呢?它是包含路由记录的一个对象,每个属性值名是每个记录的path属性值,属性值就是具有这个path属性值的路由记录。这儿有一个叫路由记录的东西,这是什么意思呢?路由记录就是 routes 配置数组中的对象副本(还有在 children 数组),路由记录都是包含在matched属性中例如
const router = new vuerouter({ routes: [ // 下面的对象就是 route record { path: '/foo', component: foo, children: [ // 这也是个 route record { path: 'bar', component: bar } ] } ] })
在上面代码中用一段代码用于给每个route添加路由记录,那么路由记录的实现是如何的呢,下面是addroutereord()的实现
function addrouterecord ( pathlist, pathmap, namemap, route, parent, matchas ) { var path = route.path; var name = route.name; var normalizedpath = normalizepath( path, parent ); var record = { path: normalizedpath, regex: compilerouteregex(normalizedpath, pathtoregexpoptions), components: route.components || { default: route.component }, instances: {}, name: name, parent: parent, matchas: matchas, redirect: route.redirect, beforeenter: route.beforeenter, meta: route.meta || {}, props: route.props == null ? {} : route.components ? route.props : { default: route.props } }; if (route.children) { route.children.foreach(function (child) { addrouterecord(pathlist, pathmap, namemap, child, record, childmatchas); }); } if (route.alias !== undefined) { // 如果有别名的情况 } if (!pathmap[record.path]) { pathlist.push(record.path); pathmap[record.path] = record; } }
addrouterecord()这个函数的参数我都懒得说什么意思了,新增的parent也表示路由记录,首先获取path,name。然后通过normalizepath()规范格式,然后就是record这个对象的建立,然后遍历routes的子元素添加路由记录如果有别名的情况还需要考虑别名的情况然后更新path map。
history我们在回到vuerouter的构造函数中,往下看是模式的选择,一共这么几种模式一种history,hash和abstract三种。· 默认hash: 使用url hash值作为路由,支持所有浏览器
· history: 依赖html5 history api和服务器配置
· abstract:支持所有 javascript 运行环境,如 node.js 服务器端。如果发现没有浏览器的 api,路由会自动强制进入这个模式。
默认是hash,路由通过“#”隔开,但是如果工程中有锚链接或者路由中有hash值,原先的“#”就会对页面跳转产生影响;所以就需要使用history模式。
在应用中我们常用的基本都是history模式,下面我们来看看hashhistory的构造函数
var history = function history (router, base) { this.router = router; this.base = normalizebase(base); this.current = start; this.pending = null; this.ready = false; this.readycbs = []; this.readyerrorcbs = []; this.errorcbs = []; };
因为hash和history有一些相同的地方,所以hashhistory会在history构造函数上进行扩展下面是各个属性所代表的意义:
this.router表示vuerouter实例
this.base表示应用的基路径。例如,如果整个单页应用服务在 /app/ 下,然后 base 就应该设为
"/app/"。normalizebase()用于格式化base
this.current开始时的route,route使用createroute()创建
this.pending表示进行时的route
this.ready表示准备状态
this.readycbs表示准备回调函数
creatroute()在文件src/util/route.js中,下面是他的实现
function createroute ( record, location, redirectedfrom, router ) { var stringifyquery$$1 = router && router.options.stringifyquery; var query = location.query || {}; try { query = clone(query); } catch (e) {} var route = { name: location.name || (record && record.name), meta: (record && record.meta) || {}, path: location.path || '/', hash: location.hash || '', query: query, params: location.params || {}, fullpath: getfullpath(location, stringifyquery$$1), matched: record ? formatmatch(record) : [] }; if (redirectedfrom) { route.redirectedfrom = getfullpath(redirectedfrom, stringifyquery$$1); } return object.freeze(route) }
createroute有三个参数,record表示路由记录,location,redirectedfrom表示url地址信息对象,router表示vuerouter实例对象。通过传入的参数,返回一个冻结的route对象,route对象里边包含了一些有关location的属性。history包含了一些基本的方法,例如比较重要的方法有transitionto(),下面是transitionto()的具体实现。
history.prototype.transitionto = function transitionto (location, oncomplete, onabort) { var this$1 = this; var route = this.router.match(location, this.current); this.confirmtransition(route, function () { this$1.updateroute(route); oncomplete && oncomplete(route); this$1.ensureurl(); // fire ready cbs once if (!this$1.ready) { this$1.ready = true; this$1.readycbs.foreach(function (cb) { cb(route); }); } }, function (err) { if (onabort) { onabort(err); } if (err && !this$1.ready) { this$1.ready = true; this$1.readyerrorcbs.foreach(function (cb) { cb(err); }); } }); };
首先match得到匹配的route对象,route对象在之前已经提到过。然后使用confirmtransition()确认过渡,更新route,ensureurl()的作用就是更新url。如果ready为false,更改ready的值,然后对readycbs数组进行遍历回调。下面来看看html5history的构造函数
var html5history = (function (history$$1) { function html5history (router, base) { var this$1 = this; history$$1.call(this, router, base); var initlocation = getlocation(this.base); window.addeventlistener('popstate', function (e) { var current = this$1.current; var location = getlocation(this$1.base); if (this$1.current === start && location === initlocation) { return } }); } if ( history$$1 ) html5history.__proto__ = history$$1; html5history.prototype = object.create( history$$1 && history$$1.prototype ); html5history.prototype.constructor = html5history; html5history.prototype.push = function push (location, oncomplete, onabort) { var this$1 = this; var ref = this; var fromroute = ref.current; this.transitionto(location, function (route) { pushstate(cleanpath(this$1.base + route.fullpath)); handlescroll(this$1.router, route, fromroute, false); oncomplete && oncomplete(route); }, onabort); }; html5history.prototype.replace = function replace (location, oncomplete, onabort) { var this$1 = this; var ref = this; var fromroute = ref.current; this.transitionto(location, function (route) { replacestate(cleanpath(this$1.base + route.fullpath)); handlescroll(this$1.router, route, fromroute, false); oncomplete && oncomplete(route); }, onabort); }; return html5history; }(history))
在html5history()中代码多次用到了getlocation()那我们来看看他的具体实现吧
function getlocation (base) { var path = window.location.pathname; if (base && path.indexof(base) === 0) { path = path.slice(base.length); } return (path || '/') + window.location.search + window.location.hash }
用一个简单的地址来解释代码中各个部分的含义。例如http://example.com:1234/test/test.htm#part2?a=123,window.location.pathname=>/test/test.htm=>?a=123,window.location.hash=>#part2。
把我们继续回到html5history()中,首先继承history构造函数。然后监听popstate事件。当活动记录条目更改时,将触发popstate事件。需要注意的是调用history.pushstate()或history.replacestate()不会触发popstate事件。我们来看看html5history的push方法。location表示url信息,oncomplete表示成功后的回调函数,onabort表示失败的回调函数。首先获取current属性值,replacestate和pushstate用于更新url,然后处理滚动。模式的选择就大概讲完了,我们回到入口文件,看看init()方法,app代表的是vue的实例,现将app存入this.apps中,如果this.app已经存在就返回,如果不是就赋值。this.history是三种的实例对象,然后分情况进行transtionto()操作,history方法就是给history.cb赋值穿进去的回调函数。
下面看getmatchedcomponents(),唯一需要注意的就是我们多次提到的route.matched是路由记录的数据,最终返回的是每个路由记录的components属性值的值。
router-view最后讲讲router-view
var view = { name: 'router-view', functional: true, props: { name: { type: string, default: 'default' } }, render: function render (_, ref) { var props = ref.props; var children = ref.children; var parent = ref.parent; var data = ref.data; // 解决嵌套深度问题 data.routerview = true; var h = parent.$createelement; var name = props.name; // route var route = parent.$route; // 缓存 var cache = parent._routerviewcache || (parent._routerviewcache = {}); // 组件的嵌套深度 var depth = 0; // 用于设置class值 var inactive = false; // 组件的嵌套深度 while (parent && parent._routerroot !== parent) { if (parent.$vnode && parent.$vnode.data.routerview) { depth++; } if (parent._inactive) { inactive = true; } parent = parent.$parent; } data.routerviewdepth = depth; if (inactive) { return h(cache[name], data, children) } var matched = route.matched[depth]; if (!matched) { cache[name] = null; return h() } var component = cache[name] = matched.components[name]; data.registerrouteinstance = function (vm, val) { // val could be undefined for unregistration var current = matched.instances[name]; if ( (val && current !== vm) || (!val && current === vm) ) { matched.instances[name] = val; } } ;(data.hook || (data.hook = {})).prepatch = function (_, vnode) { matched.instances[name] = vnode.componentinstance; }; var propstopass = data.props = resolveprops(route, matched.props && matched.props[name]); if (propstopass) { propstopass = data.props = extend({}, propstopass); var attrs = data.attrs = data.attrs || {}; for (var key in propstopass) { if (!component.props || !(key in component.props)) { attrs[key] = propstopass[key]; delete propstopass[key]; } } } return h(component, data, children) } };
router-view比较简单,functional为true使组件无状态 (没有 data ) 和无实例 (没有 this 上下文)。他们用一个简单的 render 函数返回虚拟节点使他们更容易渲染。props表示接受属性,下面来看看render函数,首先获取数据,然后缓存,_inactive用于处理keep-alive情况,获取路由记录,注册route实例,h()用于渲染。很简单我也懒得一一再说。
相关推荐:
vue-router的权限控制代码分享
vue-router结合transition实现app动画切换效果实例分享
三种vue-router实现组件间跳转的方法
以上就是vue-router源码实例详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product