路由这个概念最早是后端出现的。在之前用模板引擎开发页面时,常常会看到这样html
http://www.xxx.com/login
大体流程能够当作这样:前端
浏览器发出请求vue
服务器监听到80端口(或443)有请求过来,并解析url路径git
根据服务器的路由配置,返回相应信息(能够是 html 字串,也能够是 json 数据,图片等)github
浏览器根据数据包的 Content-Type 来决定如何解析数据ajax
简单来讲路由就是用来跟后端服务器进行交互的一种方式,经过不一样的路径,来请求不一样的资源,请求不一样的页面是路由的其中一种功能。vue-router
随着 ajax 的流行,异步数据请求交互运行在不刷新浏览器的状况下进行。而异步交互体验的更高级版本就是 SPA —— 单页应用。单页应用不只仅是在页面交互是无刷新的,连页面跳转都是无刷新的,为了实现单页应用,因此就有了前端路由。
相似于服务端路由,前端路由实现起来其实也很简单,就是匹配不一样的 url 路径,进行解析,而后动态的渲染出区域 html 内容。可是这样存在一个问题,就是 url 每次变化的时候,都会形成页面的刷新。那解决问题的思路即是在改变 url 的状况下,保证页面的不刷新。在 2014 年以前,你们是经过 hash 来实现路由,url hash 就是相似于:express
http://www.xxx.com/#/login
这种 #。后面 hash 值的变化,并不会致使浏览器向服务器发出请求,浏览器不发出请求,也就不会刷新页面。另外每次 hash 值的变化,还会触发hashchange
这个事件,经过这个事件咱们就能够知道 hash 值发生了哪些变化。而后咱们即可以监听hashchange
来实现更新页面部份内容的操做:json
function matchAndUpdate () { // todo 匹配 hash 作 dom 更新操做 } window.addEventListener('hashchange', matchAndUpdate)
14年后,由于HTML5标准发布。多了两个 API,pushState
和 replaceState
,经过这两个 API 能够改变 url 地址且不会发送请求。同时还有popstate
事件。经过这些就能用另外一种方式来实现前端路由了,但原理都是跟 hash 实现相同的。用了 HTML5 的实现,单页路由的 url 就不会多出一个#,变得更加美观。但由于没有 # 号,因此当用户刷新页面之类的操做时,浏览器仍是会给服务器发送请求。为了不出现这种状况,因此这个实现须要服务器的支持,须要把全部路由都重定向到根页面。后端
function matchAndUpdate () { // todo 匹配路径 作 dom 更新操做 } window.addEventListener('popstate', matchAndUpdate)
咱们来看一下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
的世界。
vue-router 实现 -- new VueRouter(options)
通过上面的阐述,相信您已经对前端路由以及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
模式的实现,这里咱们能够沿用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}`) } }
到这里也就基本上结束了。源码地址:
有兴趣能够本身玩玩。实现的比较粗陋,若有疑问,欢迎指点。