Skip to content

Instantly share code, notes, and snippets.

@bponomarenko
Last active April 7, 2023 13:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bponomarenko/253c64d355373b8e7afccc11581b240a to your computer and use it in GitHub Desktop.
Save bponomarenko/253c64d355373b8e7afccc11581b240a to your computer and use it in GitHub Desktop.
Custom implementation of the missing onAbort hooks in vue-router
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,
...
});
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