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

feat(hash):增加hash路由

parent 121a1256
...@@ -21,7 +21,7 @@ const routes = [ ...@@ -21,7 +21,7 @@ const routes = [
] ]
const router = new VueRouter({ const router = new VueRouter({
mode: 'history', // mode: 'history',
base: process.env.BASE_URL, base: process.env.BASE_URL,
routes routes
}) })
......
...@@ -9,7 +9,6 @@ export default class VueRouter { ...@@ -9,7 +9,6 @@ export default class VueRouter {
// 把Vue构造函数记录到全局变量 // 把Vue构造函数记录到全局变量
_Vue = Vue _Vue = Vue
// 把创建Vue实例时候传入的router对象注入到vue实例中 // 把创建Vue实例时候传入的router对象注入到vue实例中
//
// 混入 // 混入
_Vue.mixin({ _Vue.mixin({
beforeCreate() { beforeCreate() {
...@@ -25,11 +24,14 @@ export default class VueRouter { ...@@ -25,11 +24,14 @@ export default class VueRouter {
this.options = options this.options = options
this.routeMap = {} this.routeMap = {}
this.data = _Vue.observable({ this.data = _Vue.observable({
current: window.location.pathname current: window.location.pathname
}) })
} }
init(){ init(){
if(!(this.options.mode && this.options.mode === 'history') && !window.location.hash){
window.location.hash = '#/'
}
this.createRouteMap() this.createRouteMap()
this.initComponents(_Vue) this.initComponents(_Vue)
this.initEvent() this.initEvent()
...@@ -43,6 +45,7 @@ export default class VueRouter { ...@@ -43,6 +45,7 @@ export default class VueRouter {
} }
initComponents(Vue){ initComponents(Vue){
const self = this
Vue.component('router-link', { Vue.component('router-link', {
props:{ props:{
to: String to: String
...@@ -60,14 +63,17 @@ export default class VueRouter { ...@@ -60,14 +63,17 @@ export default class VueRouter {
}, },
methods:{ methods:{
clickHandler(e){ clickHandler(e){
history.pushState({},'', this.to) if(self.options.mode && self.options.mode === 'history'){
history.pushState({},'', this.to)
} else {
location.hash = `#${this.to}`
}
this.$router.data.current = this.to this.$router.data.current = this.to
e.preventDefault(); e.preventDefault();
} }
} }
}) })
const self = this
Vue.component('router-view', { Vue.component('router-view', {
render(h){ render(h){
const component = self.routeMap[self.data.current] const component = self.routeMap[self.data.current]
...@@ -77,8 +83,15 @@ export default class VueRouter { ...@@ -77,8 +83,15 @@ export default class VueRouter {
} }
initEvent(){ initEvent(){
window.addEventListener('popstate',()=>{ if(this.options.mode && this.options.mode === 'history'){
this.data.current = window.location.pathname 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