From 84398aedac8b9203b236a7c128ebc7d10a04e4a5 Mon Sep 17 00:00:00 2001 From: Calvin Liang Date: Thu, 18 Jun 2020 06:38:36 -0700 Subject: [PATCH] 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 --- src/index.js | 13 ++++++++++++- test/e2e/specs/scroll-behavior.js | 14 ++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index d0fb34b7b..ae3b69e15 100644 --- a/src/index.js +++ b/src/index.js @@ -8,6 +8,7 @@ import { cleanPath } from './util/path' import { createMatcher } from './create-matcher' import { normalizeLocation } from './util/location' import { supportsPushState } from './util/push-state' +import { handleScroll } from './util/scroll' import { HashHistory } from './history/hash' import { HTML5History } from './history/html5' @@ -117,8 +118,18 @@ export default class VueRouter { const history = this.history if (history instanceof HTML5History || history instanceof HashHistory) { - const setupListeners = () => { + const handleInitialScroll = (routeOrError) => { + const from = history.current + const expectScroll = this.options.scrollBehavior + const supportsScroll = supportsPushState && expectScroll + + if (supportsScroll && 'fullPath' in routeOrError) { + handleScroll(this, routeOrError, from, false) + } + } + const setupListeners = (routeOrError) => { history.setupListeners() + handleInitialScroll(routeOrError) } history.transitionTo(history.getCurrentLocation(), setupListeners, setupListeners) } diff --git a/test/e2e/specs/scroll-behavior.js b/test/e2e/specs/scroll-behavior.js index 12119ed0b..db317d591 100644 --- a/test/e2e/specs/scroll-behavior.js +++ b/test/e2e/specs/scroll-behavior.js @@ -119,6 +119,20 @@ module.exports = { null, 'scroll to anchor that starts with number' ) + + .url('http://localhost:8080/scroll-behavior/bar#anchor') + .execute(function () { + location.reload(true) + }) + .waitForElementVisible('#app', 1000) + .assert.evaluate( + function () { + return document.getElementById('anchor').getBoundingClientRect().top < 1 + }, + null, + 'scroll to anchor on load' + ) + .end() } }