Skip to content

Commit 84398ae

Browse files
Calvin-LLposva
andauthored
fix(scroll): run scrollBehavior on initial load (fix #3196) (#3199)
* Add handleScroll on initial history.transitionTo * Update index.js * test(scroll-behavior): add tests for scrollBehavior on load * refactor(scroll-behavior): scrollBehavior on load * style: remove spaces * fix: handleScroll not called with from * test(scroll-behavior): remove redundant tests * fix: call handleScroll only if initial navigation succeeds Co-authored-by: Eduardo San Martin Morote <[email protected]>
1 parent bee5d73 commit 84398ae

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/index.js

+12-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { cleanPath } from './util/path'
88
import { createMatcher } from './create-matcher'
99
import { normalizeLocation } from './util/location'
1010
import { supportsPushState } from './util/push-state'
11+
import { handleScroll } from './util/scroll'
1112

1213
import { HashHistory } from './history/hash'
1314
import { HTML5History } from './history/html5'
@@ -117,8 +118,18 @@ export default class VueRouter {
117118
const history = this.history
118119

119120
if (history instanceof HTML5History || history instanceof HashHistory) {
120-
const setupListeners = () => {
121+
const handleInitialScroll = (routeOrError) => {
122+
const from = history.current
123+
const expectScroll = this.options.scrollBehavior
124+
const supportsScroll = supportsPushState && expectScroll
125+
126+
if (supportsScroll && 'fullPath' in routeOrError) {
127+
handleScroll(this, routeOrError, from, false)
128+
}
129+
}
130+
const setupListeners = (routeOrError) => {
121131
history.setupListeners()
132+
handleInitialScroll(routeOrError)
122133
}
123134
history.transitionTo(history.getCurrentLocation(), setupListeners, setupListeners)
124135
}

test/e2e/specs/scroll-behavior.js

+14
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,20 @@ module.exports = {
119119
null,
120120
'scroll to anchor that starts with number'
121121
)
122+
123+
.url('http://localhost:8080/scroll-behavior/bar#anchor')
124+
.execute(function () {
125+
location.reload(true)
126+
})
127+
.waitForElementVisible('#app', 1000)
128+
.assert.evaluate(
129+
function () {
130+
return document.getElementById('anchor').getBoundingClientRect().top < 1
131+
},
132+
null,
133+
'scroll to anchor on load'
134+
)
135+
122136
.end()
123137
}
124138
}

0 commit comments

Comments
 (0)