Commit 01918096 authored by 尚斌杰's avatar 尚斌杰

feat(hash):增加hash路由

parent 121a1256
......@@ -21,7 +21,7 @@ const routes = [
]
const router = new VueRouter({
mode: 'history',
// mode: 'history',
base: process.env.BASE_URL,
routes
})
......
......@@ -9,7 +9,6 @@ export default class VueRouter {
// 把Vue构造函数记录到全局变量
_Vue = Vue
// 把创建Vue实例时候传入的router对象注入到vue实例中
//
// 混入
_Vue.mixin({
beforeCreate() {
......@@ -30,6 +29,9 @@ export default class VueRouter {
}
init(){
if(!(this.options.mode && this.options.mode === 'history') && !window.location.hash){
window.location.hash = '#/'
}
this.createRouteMap()
this.initComponents(_Vue)
this.initEvent()
......@@ -43,6 +45,7 @@ export default class VueRouter {
}
initComponents(Vue){
const self = this
Vue.component('router-link', {
props:{
to: String
......@@ -60,14 +63,17 @@ export default class VueRouter {
},
methods:{
clickHandler(e){
if(self.options.mode && self.options.mode === 'history'){
history.pushState({},'', this.to)
} else {
location.hash = `#${this.to}`
}
this.$router.data.current = this.to
e.preventDefault();
}
}
})
const self = this
Vue.component('router-view', {
render(h){
const component = self.routeMap[self.data.current]
......@@ -77,8 +83,15 @@ export default class VueRouter {
}
initEvent(){
if(this.options.mode && this.options.mode === 'history'){
window.addEventListener('popstate',()=>{
this.data.current = window.location.pathname
})
} else {
window.addEventListener('hashchange',()=>{
this.data.current = window.location.hash.replace('#','')
})
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment