-
-
Save bisubus/def44e634a8cbd0e06be834c35a762d7 to your computer and use it in GitHub Desktop.
Custom implementation of the missing onAbort hooks in vue-router
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue from 'vue'; | |
import VueRouter from 'vue-router'; | |
import applyOnRouterAbortShim from './on-router-abort-shim'; | |
Vue.use(VueRouter); | |
const router = new VueRouter(...); | |
applyOnRouterAbortShim(router); | |
new Vue({ | |
router, | |
... | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import VueRouter from 'vue-router'; | |
/** | |
* This shim adds support for onAbort global hook (similar to onError by behavior), which allows to | |
* register callbacks for aborted navigations globally. | |
* At the moment, library doesn't support this api out of the box. This solution is based on workaround | |
* proposed in https://github.com/vuejs/vue-router/issues/3157 ticket. | |
*/ | |
const abortCallbacks = []; | |
// Registers onAbort callback | |
VueRouter.prototype.onAbort = callback => { | |
abortCallbacks.push(callback); | |
}; | |
const processAbortCallbacks = () => { | |
abortCallbacks.forEach(callback => { | |
callback(); | |
}); | |
}; | |
export default router => { | |
// "router.history" is undocumented api, but it is the only way to handle aborted navigations as of now | |
const historyTransitionTo = router.history.constructor.prototype.transitionTo; | |
// This method will be called for both "router.push" and "router.replace" methods under the hood | |
router.history.constructor.prototype.transitionTo = function extendedTransitionTo(location, onComplete, onAbort) { | |
return historyTransitionTo.call(this, location, onComplete, error => { | |
processAbortCallbacks(); | |
if (onAbort) { | |
onAbort(error); | |
} | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment