准备:
插件、slot插槽,混入、render函数、运行时和完整版的Vue
Vue.use(VueRouter)
const router=newVueRouter({
routes: [
{ name: 'home', path: '/', component: homeComponent }
]
})
new Vue({router,render: h=>h(App)})
.$mount('#app')
实现思路
- 创建 VueRouter 插件,静态方法 install
-
-
- 创建 VueRouter 类
-
- 初始化,options、routeMap、app(简化操作,创建 Vue 实例作为响应式数据记录当前路径)
-
- initRouteMap() 遍历所有路由信息,把组件和路由的映射记录到 routeMap 对象中
-
- 注册 popstate 事件,当路由地址发生变化,重新记录当前的路径
-
- 创建 router-link 和 router-view 组件
-
- 当路径改变的时候通过当前路径在 routerMap 对象中找到对应的组件,渲染 router-view
代码实现
import Vue from 'vue'
let _Vue = null
export default class VueRouter {
static install () {
if (VueRouter.install.installed) {
return
}
VueRouter.install.installed = true
_Vue = Vue
_Vue.mixin({
beforeCreate () {
if (this.$options.router) {
_Vue.prototype.$router = this.$options.router
this.$router.init()
}
}
})
}
constructor (options) {
this.options = options
this.routeMap = {}
this.data = _Vue.observable({
current: '/'
})
}
init () {
this.createRouteMap()
this.initComponent(_Vue)
this.initEvent()
}
createRouteMap () {
this.options.routes.forEach(route => {
this.routeMap[route.path] = route.component
})
}
initComponent (Vue) {
Vue.component('router-link', {
props: {
to: String
},
render (h) {
return h('a', {
attrs: {
href: this.to
},
on: {
click: this.clickHander
}
}, [this.$slots.default])
},
methods: {
clickHander (e) {
history.pushState({}, '', this.to)
this.$router.data.current = this.to
e.preventDefault()
}
}
})
const self = this
Vue.component('router-view', {
render (h) {
const path = self.data.current
const compnent = self.routeMap[path]
return h(compnent)
}
})
}
initEvent () {
window.addEventListener('popstate', () => {
this.data.current = window.location.pathname
})
}
}