Skip to content

Commit

Permalink
fix(guards): remove registered update guards after leaving
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Jul 21, 2020
1 parent dc476ec commit 41bffda
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 13 deletions.
43 changes: 43 additions & 0 deletions __tests__/guards/onBeforeRouteUpdate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,47 @@ describe('onBeforeRouteUpdate', () => {
await router.push('/foo?q')
expect(spy).toHaveBeenCalledTimes(1)
})

it('removes update guards when leaving', async () => {
expect.assertions(3)
const spy = jest
.fn()
.mockImplementation(function (this: any, to, from, next) {
expect(typeof this.counter).toBe('number')
next()
})
const WithLeave = defineComponent({
template: `text`,
// we use data to check if the context is the right one because saving `this` in a variable logs a few warnings
data: () => ({ counter: 0 }),
setup() {
onBeforeRouteUpdate(spy)
},
})

const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/', component },
{ path: '/foo', component: WithLeave as any },
],
})
const app = createApp({
template: `
<router-view />
`,
})
app.use(router)
const rootEl = document.createElement('div')
document.body.appendChild(rootEl)
app.mount(rootEl)

await router.isReady()
await router.push('/foo')
await router.push('/foo?q')
await router.push('/')
await router.push('/foo')
await router.push('/foo?q')
expect(spy).toHaveBeenCalledTimes(2)
})
})
13 changes: 0 additions & 13 deletions src/navigationGuards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,16 +260,3 @@ function isRouteComponent(
'__vccOpts' in component
)
}

/**
* 1. beforeRouteEnter callbacks
* 2. Dictionary of instances per view name
*/
export type GuardManagerEntry = [
NavigationGuardNextCallback[],
Record<string, ComponentPublicInstance | undefined | null>
]

export function createGuardManager() {
return new Map<RouteRecordNormalized, GuardManagerEntry>()
}
1 change: 1 addition & 0 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,7 @@ export function createRouter(options: RouterOptions): Router {
for (const record of leavingRecords) {
// remove registered guards from removed matched records
record.leaveGuards = []
record.updateGuards = []
// free the references
record.instances = {}
record.enterCallbacks = {}
Expand Down

0 comments on commit 41bffda

Please sign in to comment.