UNPKG

2.96 kBJavaScriptView Raw
1<% if (router.scrollBehavior) { %>
2<%= isTest ? '/* eslint-disable quotes, semi, indent, comma-spacing, key-spacing, object-curly-spacing, space-before-function-paren */' : '' %>
3export default <%= serializeFunction(router.scrollBehavior) %>
4<%= isTest ? '/* eslint-enable quotes, semi, indent, comma-spacing, key-spacing, object-curly-spacing, space-before-function-paren */' : '' %>
5<% } else { %>import { getMatchedComponents } from './utils'
6
7if (process.client) {
8 if ('scrollRestoration' in window.history) {
9 window.history.scrollRestoration = 'manual'
10
11 // reset scrollRestoration to auto when leaving page, allowing page reload
12 // and back-navigation from other pages to use the browser to restore the
13 // scrolling position.
14 window.addEventListener('beforeunload', () => {
15 window.history.scrollRestoration = 'auto'
16 })
17
18 // Setting scrollRestoration to manual again when returning to this page.
19 window.addEventListener('load', () => {
20 window.history.scrollRestoration = 'manual'
21 })
22 }
23}
24
25 export default function (to, from, savedPosition) {
26 // If the returned position is falsy or an empty object, will retain current scroll position
27 let position = false
28
29 const Pages = getMatchedComponents(to)
30
31 // Scroll to the top of the page if...
32 if (
33 // One of the children set `scrollToTop`
34 Pages.some(Page => Page.options.scrollToTop) ||
35 // scrollToTop set in only page without children
36 (Pages.length < 2 && Pages.every(Page => Page.options.scrollToTop !== false))
37 ) {
38 position = { x: 0, y: 0 }
39 }
40
41 // savedPosition is only available for popstate navigations (back button)
42 if (savedPosition) {
43 position = savedPosition
44 }
45
46 const nuxt = window.<%= globals.nuxt %>
47
48 if (
49 // Route hash changes
50 (to.path === from.path && to.hash !== from.hash) ||
51 // Initial load (vuejs/vue-router#3199)
52 to === from
53 ) {
54 nuxt.$nextTick(() => nuxt.$emit('triggerScroll'))
55 }
56
57 return new Promise((resolve) => {
58 // wait for the out transition to complete (if necessary)
59 nuxt.$once('triggerScroll', () => {
60 // coords will be used if no selector is provided,
61 // or if the selector didn't match any element.
62 if (to.hash) {
63 let hash = to.hash
64 // CSS.escape() is not supported with IE and Edge.
65 if (typeof window.CSS !== 'undefined' && typeof window.CSS.escape !== 'undefined') {
66 hash = '#' + window.CSS.escape(hash.substr(1))
67 }
68 try {
69 if (document.querySelector(hash)) {
70 // scroll to anchor by returning the selector
71 position = { selector: hash }
72 }
73 } catch (e) {
74 <%= isTest ? '// eslint-disable-next-line no-console' : '' %>
75 console.warn('Failed to save scroll position. Please add CSS.escape() polyfill (https://github.com/mathiasbynens/CSS.escape).')
76 }
77 }
78 resolve(position)
79 })
80 })
81}
82<% } %>