From 2b16d8b2ace74e94df82e1109f4578dae33c2eb0 Mon Sep 17 00:00:00 2001 From: andy-viv Date: Fri, 25 May 2018 05:47:58 -0700 Subject: [PATCH] added "hashChangeStart" and "hashChangeComplete" events (#4234) This PR adds events for when there is a hash-only change in the URL. This is needed because `window.addEventListener('hashchange', ...)` does not work with next.js because it is using pushState. --- lib/router/index.js | 2 +- lib/router/router.js | 2 ++ readme.md | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/router/index.js b/lib/router/index.js index 94586c78..1e4be58b 100644 --- a/lib/router/index.js +++ b/lib/router/index.js @@ -15,7 +15,7 @@ const SingletonRouter = { // Create public properties and methods of the router in the SingletonRouter const propertyFields = ['components', 'pathname', 'route', 'query', 'asPath'] -const routerEvents = ['routeChangeStart', 'beforeHistoryChange', 'routeChangeComplete', 'routeChangeError'] +const routerEvents = ['routeChangeStart', 'beforeHistoryChange', 'routeChangeComplete', 'routeChangeError', 'hashChangeStart', 'hashChangeComplete'] const coreMethodFields = ['push', 'replace', 'reload', 'back', 'prefetch', 'beforePopState'] propertyFields.forEach((field) => { diff --git a/lib/router/router.js b/lib/router/router.js index 5193be43..15e456a4 100644 --- a/lib/router/router.js +++ b/lib/router/router.js @@ -148,8 +148,10 @@ export default class Router { // If the url change is only related to a hash change // We should not proceed. We should only change the state. if (this.onlyAHashChange(as)) { + this.events.emit('hashChangeStart', as) this.changeState(method, url, as) this.scrollToHash(as) + this.events.emit('hashChangeComplete', as) return true } diff --git a/readme.md b/readme.md index 74862bff..f0a02893 100644 --- a/readme.md +++ b/readme.md @@ -555,6 +555,8 @@ Here's a list of supported events: - `onRouteChangeComplete(url)` - Fires when a route changed completely - `onRouteChangeError(err, url)` - Fires when there's an error when changing routes - `onBeforeHistoryChange(url)` - Fires just before changing the browser's history +- `onHashChangeStart(url)` - Fires when the hash will change but not the page +- `onHashChangeComplete(url)` - Fires when the hash has changed but not the page > Here `url` is the URL shown in the browser. If you call `Router.push(url, as)` (or similar), then the value of `url` will be `as`.