class HistoryRoute {
constructor() {
this.current = null
}
}
class VueRouter {
constructor(options) {
this.mode = options.mode || 'hash'
this.routes = options.routes || []
this.routesMap = this.createMap(this.routes)
this.history = new HistoryRoute()
this.init()
}
init() {
if (this.mode === 'hash') {
if (!location.hash) {
location.hash = '/'
}
window.addEventListener('load', () => {
console.log('load')
this.history.current = location.hash.slice(1)
})
window.addEventListener('hashchange', () => {
console.log('hashchange')
this.history.current = location.hash.slice(1)
})
} else {
if (location.hash) {
location.pathname = '/'
}
window.addEventListener('load', () => {
console.log('load')
this.history.current = location.pathname
})
window.addEventListener('popstate', () => {
console.log('popstate')
this.history.current = location.pathname
})
}
}
createMap(routes) {
return routes.reduce((memo, current) => {
memo[current.path] = current.component
return memo
}, {})
}
go() {
}
push(path) {
window.history.pushState({}, '', path)
this.history.current = path
}
back() {
}
afterEach() {
console.log('after')
}
beforeEach() {
}
}
VueRouter.install = function (Vue) {
console.log(Vue, 'install')
Vue.mixin({
beforeCreate() {
if (this.$options && this.$options.router) { // 定位根组件
this._root = this
this._router = this.$options.router
Vue.util.defineReactive(this, 'xxx', this._router.history)
} else { // 子节点
try {
this._root = this.$parent._root
} catch (e) {
console.log(this, e)
}
}
Object.defineProperty(this, '$router', {
get() {
return this._root._router
}
})
Object.defineProperty(this, '$route', {
get() {
return {
current: this._root._router.history.current
}
}
})
}
})
Vue.component('router-link', {
props: {
to: String,
tag: String
},
render(h) {
let mode = this._self._root._router.mode
let tag = this.tag || 'a'
console.log(this)
return h(tag, {
attrs: {
href: this._self._root._router.mode === 'hash' ? `#${this.to}` : this.to,
},
on: {
click: () => {
this.handleClick()
}
}
}, this.$slots.default)
},
methods: {
handleClick() {
this._root._router.push(this.to)
event.returnValue = false
}
}
})
Vue.component('router-view', {
render(h) {
let current = this._self._root._router.history.current
let routeMap = this._self._root._router.routesMap
console.log(this)
return h(routeMap[current])
}
})
}
export default VueRouter
Vue-router 简单实现
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- key words : vue-cli vue-router webpack 在vue-cli+vue-route...
- 直接贴路由配置文件代码 说明:在这里我们 router 的 meta属性 添加了 自定义的breadcrumb对象...
- github地址https://github.com/JohnnyZhangQiao/vue-family 如果对...
- vuex-router-sync 插件通过动态注册模块将 vue-router 和 vuex 结合在一起,实现应...