Skip to content

Commit cac351f

Browse files
committed
use location.replace when formatting hash (fix #4 & #5)
1 parent f2ca657 commit cac351f

File tree

2 files changed

+31
-10
lines changed

2 files changed

+31
-10
lines changed

src/index.js

+28-9
Original file line numberDiff line numberDiff line change
@@ -99,22 +99,24 @@ p.redirect = function (map) {
9999
*/
100100

101101
p.go = function (path, options) {
102+
var replace = options && options.replace
102103
if (this._pushstate) {
103104
// make it relative to root
104105
path = this._root
105106
? this._root + '/' + path.replace(/^\//, '')
106107
: path
107-
if (options && options.replace) {
108+
if (replace) {
108109
history.replaceState({}, '', path)
109110
} else {
110111
history.pushState({}, '', path)
111112
}
112113
this._match(path)
113114
} else {
114115
path = path.replace(/^#!?/, '')
115-
location.hash = this._hashbang
116+
var hash = this._hashbang
116117
? '!' + path
117118
: path
119+
setHash(hash, replace)
118120
}
119121
}
120122

@@ -150,15 +152,16 @@ p.initHashMode = function () {
150152
var self = this
151153
this.onRouteChange = function () {
152154
// format hashbang
153-
if (
154-
self._hashbang &&
155-
location.hash &&
156-
location.hash.charAt(1) !== '!'
157-
) {
158-
location.hash = '!' + location.hash.slice(1)
155+
var hash = location.hash
156+
if (self._hashbang && hash && hash.charAt(1) !== '!') {
157+
setHash('!' + hash.slice(1), true)
159158
return
160159
}
161-
var hash = location.hash.replace(/^#!?/, '')
160+
if (!self._hashbang && hash && hash.charAt(1) === '!') {
161+
setHash(hash.slice(1), true)
162+
return
163+
}
164+
hash = hash.replace(/^#!?/, '')
162165
var url = hash + location.search
163166
url = decodeURI(url)
164167
self._match(url)
@@ -282,4 +285,20 @@ VueRouter.install = function (Vue) {
282285
require('./link')(Vue)
283286
}
284287

288+
/**
289+
* Set current hash
290+
*
291+
* @param {String} hash
292+
* @param {Boolean} replace
293+
*/
294+
function setHash (hash, replace) {
295+
if (replace) {
296+
var urlLength = location.href.length - location.hash.length
297+
var fullURL = location.href.slice(0, urlLength) + '#' + hash
298+
location.replace(fullURL)
299+
} else {
300+
location.hash = hash
301+
}
302+
}
303+
285304
module.exports = VueRouter

src/view.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ module.exports = function (Vue) {
6262
if (route._router._hasPushState) {
6363
history.back()
6464
} else if (previousRoute) {
65-
route._router.go(previousRoute.path)
65+
route._router.go(previousRoute.path, {
66+
replace: true
67+
})
6668
}
6769
return
6870
}

0 commit comments

Comments
 (0)