diff --git a/examples/scroll-behavior/app.js b/examples/scroll-behavior/app.js index e4c40d057..4f1bbb3d1 100644 --- a/examples/scroll-behavior/app.js +++ b/examples/scroll-behavior/app.js @@ -25,23 +25,27 @@ const scrollBehavior = function (to, from, savedPosition) { // savedPosition is only available for popstate navigations. return savedPosition } else { - return new Promise(resolve => { - const position = {} - let delay = 500 - // new navigation. - // scroll to anchor by returning the selector - if (to.hash) { - position.selector = to.hash + const position = {} + + // scroll to anchor by returning the selector + if (to.hash) { + position.selector = to.hash - // specify offset of the element - if (to.hash === '#anchor2') { - position.offset = { y: 100 } - } + // specify offset of the element + if (to.hash === '#anchor2') { + position.offset = { y: 100 } + } - if (document.querySelector(to.hash)) { - delay = 0 - } + if (document.querySelector(to.hash)) { + return position } + + // if the returned position is falsy or an empty object, + // will retain current scroll position. + return false + } + + return new Promise(resolve => { // check if any matched route config has meta that requires scrolling to top if (to.matched.some(m => m.meta.scrollToTop)) { // coords will be used if no selector is provided, @@ -49,12 +53,13 @@ const scrollBehavior = function (to, from, savedPosition) { position.x = 0 position.y = 0 } + // wait for the out transition to complete (if necessary) - setTimeout(() => { - // if the returned position is falsy or an empty object, + this.app.$root.$once('triggerScroll', () => { + // if the resolved position is falsy or an empty object, // will retain current scroll position. resolve(position) - }, delay) + }) }) } } @@ -82,9 +87,14 @@ new Vue({
  • /bar#anchor
  • /bar#anchor2
  • - + - ` + `, + methods: { + afterLeave () { + this.$root.$emit('triggerScroll') + } + } }).$mount('#app') diff --git a/src/util/scroll.js b/src/util/scroll.js index 9991adaa7..cceb03640 100644 --- a/src/util/scroll.js +++ b/src/util/scroll.js @@ -39,7 +39,7 @@ export function handleScroll ( // wait until re-render finishes before scrolling router.app.$nextTick(() => { const position = getScrollPosition() - const shouldScroll = behavior(to, from, isPop ? position : null) + const shouldScroll = behavior.call(router, to, from, isPop ? position : null) if (!shouldScroll) { return