Skip to content

Commit bfc2cea

Browse files
committed
add global afterEach hook (close #88)
1 parent 3b39bc8 commit bfc2cea

File tree

4 files changed

+48
-0
lines changed

4 files changed

+48
-0
lines changed

src/router/api.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,16 @@ export default function (Vue, Router) {
6666
this._beforeEachHook = fn
6767
}
6868

69+
/**
70+
* Set global after hook.
71+
*
72+
* @param {Function} fn
73+
*/
74+
75+
Router.prototype.afterEach = function (fn) {
76+
this._afterEachHook = fn
77+
}
78+
6979
/**
7080
* Navigate to a given path.
7181
* The path is assumed to be already decoded, and will

src/router/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ export default class Router {
4949
this._previousTransition = null
5050
this._notFoundHandler = null
5151
this._beforeEachHook = null
52+
this._afterEachHook = null
5253

5354
// feature detection
5455
this._hasPushState =

src/router/internal.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,13 @@ export default function (Vue, Router) {
194194
child.$route = route
195195
})
196196
}
197+
// call global after hook
198+
if (this._afterEachHook) {
199+
this._afterEachHook.call(null, {
200+
to: transition.to,
201+
from: transition.from
202+
})
203+
}
197204
}
198205

199206
/**

test/unit/specs/core.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,36 @@ describe('Core', function () {
446446
}
447447
})
448448

449+
it('global after', function (done) {
450+
router = new Router({ abstract: true })
451+
var App = Vue.extend({
452+
template: '<div><router-view></router-view></div>'
453+
})
454+
router.map({
455+
'/a': {
456+
component: {
457+
template: '<p>a</p>'
458+
}
459+
}
460+
})
461+
var callCount = 0
462+
router.afterEach(function (transition) {
463+
if (callCount === 0) {
464+
// initial match
465+
expect(transition.from.path).toBeUndefined()
466+
expect(transition.to.path).toBe('/')
467+
} else {
468+
// second match
469+
expect(transition.from.path).toBe('/')
470+
expect(transition.to.path).toBe('/a')
471+
done()
472+
}
473+
callCount++
474+
})
475+
router.start(App, el)
476+
router.go('/a')
477+
})
478+
449479
it('transitionOnLoad option', function (done) {
450480
router = new Router({
451481
abstract: true,

0 commit comments

Comments
 (0)