|
| 1 | +import { Plugin } from '@nuxt/types'; |
| 2 | + |
| 3 | +declare module 'vue/types/vue' { |
| 4 | + interface Vue { |
| 5 | + $scroll(): void; |
| 6 | + } |
| 7 | +} |
| 8 | + |
| 9 | +/** |
| 10 | + * How does this work? A good question. It may be buggy. |
| 11 | + * |
| 12 | + * When user navigation occurs, history is written to the browser to be used by |
| 13 | + * the back/forward buttons. This history maintains an immutable state for each |
| 14 | + * page. We are referencing one of the values of that state stack, the key. In |
| 15 | + * Chrome and Firefox, this /appears/ to be a monotonically increasing |
| 16 | + * string-encoded number. Possibly the number of milliseconds since the |
| 17 | + * page/website was first navigated to. More testing is required. |
| 18 | + * |
| 19 | + * We detect when the value on the page we're on is higher than the largest |
| 20 | + * value we've seen before. If it is, it's a new page, and we scroll. If it's |
| 21 | + * not, we rely on the user's browser settings to decide to scroll to their |
| 22 | + * previous position or not, depending on preferences. |
| 23 | + * |
| 24 | + * This function is called universally by watching to see when $route changes |
| 25 | + * in the layout for the pages. If it's broken, first confirm your page's |
| 26 | + * layout does call this.$scroll() inside of watch on $route. |
| 27 | + */ |
| 28 | +const scrollPlugin: Plugin = (_, inject) => { |
| 29 | + let historyKeyMax = 0; |
| 30 | + |
| 31 | + inject('scroll', () => { |
| 32 | + const historyKey = +history.state.key; |
| 33 | + if (historyKeyMax < historyKey) { |
| 34 | + historyKeyMax = historyKey; |
| 35 | + window.scrollTo(0, 0); |
| 36 | + } |
| 37 | + }); |
| 38 | +}; |
| 39 | + |
| 40 | +export default scrollPlugin; |
0 commit comments