diff --git a/packages/vue-router/src/viewStacks.ts b/packages/vue-router/src/viewStacks.ts index bc93111d569..3eeb0ac31ac 100644 --- a/packages/vue-router/src/viewStacks.ts +++ b/packages/vue-router/src/viewStacks.ts @@ -32,12 +32,19 @@ export const createViewStacks = (router: Router) => { * This is needed otherwise Vue Router * will not consider this component mounted * and will not run route guards that - * are written in the component. + * are written in the component. Skip pages + * remounted behind the current one by `router.go(2)`, + * since they can share the current page's route record. */ const instance = viewItem.vueComponentRef.value; - viewItem.matchedRoute.instances = { - default: instance, - }; + const isCurrentView = + findViewItemByPath(router.currentRoute.value.path, viewItem.outletId) === + viewItem; + if (isCurrentView) { + viewItem.matchedRoute.instances = { + default: instance, + }; + } /** * Run any callbacks passed to `next()` inside a @@ -236,7 +243,6 @@ export const createViewStacks = (router: Router) => { viewItem.mount = false; viewItem.ionPageElement = undefined; viewItem.ionRoute = false; - viewItem.matchedRoute.instances = {}; } }; diff --git a/packages/vue/src/components/IonRouterOutlet.ts b/packages/vue/src/components/IonRouterOutlet.ts index 81b4e0fc6e1..dc58247aaf0 100644 --- a/packages/vue/src/components/IonRouterOutlet.ts +++ b/packages/vue/src/components/IonRouterOutlet.ts @@ -296,6 +296,16 @@ export const IonRouterOutlet = /*@__PURE__*/ defineComponent({ ); const enteringEl = enteringViewItem.ionPageElement; + /** + * Views of a parameterized route (e.g. /page/:id) share a + * route record, so point it at the entering view or its + * in-component guards won't run. + */ + const enteringInstance = enteringViewItem.vueComponentRef.value; + if (enteringInstance) { + enteringViewItem.matchedRoute.instances.default = enteringInstance; + } + /** * All views that can be transitioned to must have * an `` element for transitions and lifecycle @@ -660,7 +670,25 @@ See https://ionicframework.com/docs/vue/navigation#ionpage for more information. components && components.map((c: any) => { let props = { - ref: c.vueComponentRef, + ref: (instance: any) => { + /** + * Clear the route record on unmount like RouterView + * does, otherwise it keeps the page's DOM alive. Only + * read the ref here since reading it while mounting + * re-renders the outlet. + */ + if (instance === null) { + const { instances } = c.matchedRoute; + const previousInstance = c.vueComponentRef.value; + if ( + previousInstance && + instances.default === previousInstance + ) { + instances.default = null; + } + } + c.vueComponentRef.value = instance; + }, key: c.pathname, registerIonPage: (ionPageEl: HTMLElement) => registerIonPage(c, ionPageEl), diff --git a/packages/vue/test/base/tests/unit/detached-pages.spec.ts b/packages/vue/test/base/tests/unit/detached-pages.spec.ts new file mode 100644 index 00000000000..36164dfcc91 --- /dev/null +++ b/packages/vue/test/base/tests/unit/detached-pages.spec.ts @@ -0,0 +1,188 @@ +import { enableAutoUnmount, mount } from '@vue/test-utils'; +import { afterEach, describe, expect, it } from 'vitest'; +import { setFlagsFromString } from 'v8'; +import { runInNewContext } from 'vm'; +import { createRouter, createWebHistory } from '@ionic/vue-router'; +import { IonicVue, IonApp, IonRouterOutlet, IonPage } from '@ionic/vue'; +import { waitForRouter } from './utils'; + +/** + * Exposes `gc()` so the tests can check that a page is + * released once it leaves the DOM. + */ +setFlagsFromString('--expose-gc'); +const gc: () => void = runInNewContext('gc'); + +const collectGarbage = async () => { + for (let i = 0; i < 5; i++) { + gc(); + await new Promise((r) => setTimeout(r, 0)); + } +}; + +const App = { + components: { IonApp, IonRouterOutlet }, + template: '', +}; + +const Home = { + components: { IonPage }, + template: 'Home', +}; + +const Detail = { + components: { IonPage }, + props: ['id'], + template: 'Detail {{ id }}', +}; + +const createGuardedDetail = (leftPages: string[]) => ({ + ...Detail, + beforeRouteLeave(this: { id: string }) { + leftPages.push(this.id); + }, +}); + +const Settings = { + components: { IonPage }, + template: 'Settings', +}; + +const createAppRouter = (detail = Detail) => + createRouter({ + history: createWebHistory(process.env.BASE_URL), + routes: [ + { path: '/', component: Home }, + { path: '/message/:id', component: detail, props: true }, + { path: '/settings', component: Settings }, + ], + }); + +const mountApp = async (router: ReturnType) => { + router.push('/'); + await router.isReady(); + return mount(App, { + global: { plugins: [router, IonicVue] }, + attachTo: document.body, + }); +}; + +enableAutoUnmount(afterEach); + +describe('Detached pages', () => { + it('should release a page after navigating back from it', async () => { + const router = createAppRouter(); + await mountApp(router); + + router.push('/message/1'); + await waitForRouter(); + const detailPage = new WeakRef(document.querySelector('.detail')!); + + router.back(); + await waitForRouter(); + expect(document.querySelector('.detail')).toBeNull(); + + await collectGarbage(); + expect(detailPage.deref()).toBeUndefined(); + }); + + it('should release a page after it is replaced', async () => { + const router = createAppRouter(); + await mountApp(router); + + router.push('/message/1'); + await waitForRouter(); + const detailPage = new WeakRef(document.querySelector('.detail')!); + + router.replace('/settings'); + await waitForRouter(); + expect(document.querySelector('.detail')).toBeNull(); + + await collectGarbage(); + expect(detailPage.deref()).toBeUndefined(); + }); + + it('should release a page after navigating back to a page of the same route', async () => { + const router = createAppRouter(); + await mountApp(router); + + router.push('/message/1'); + await waitForRouter(); + router.push('/message/2'); + await waitForRouter(); + const secondDetailPage = new WeakRef(document.querySelectorAll('.detail')[1]); + + router.back(); + await waitForRouter(); + expect(document.querySelectorAll('.detail').length).toBe(1); + + await collectGarbage(); + expect(secondDetailPage.deref()).toBeUndefined(); + }); + + it('should run the leave guard of the page navigated back to', async () => { + const leftPages: string[] = []; + const router = createAppRouter(createGuardedDetail(leftPages)); + await mountApp(router); + + router.push('/message/1'); + await waitForRouter(); + router.push('/message/2'); + await waitForRouter(); + + router.back(); + await waitForRouter(); + expect(router.currentRoute.value.path).toBe('/message/1'); + + router.push('/settings'); + await waitForRouter(); + + expect(leftPages).toEqual(['1']); + }); + + it('should run the leave guard of the page navigated back to with router.go()', async () => { + const leftPages: string[] = []; + const router = createAppRouter(createGuardedDetail(leftPages)); + await mountApp(router); + + router.push('/message/1'); + await waitForRouter(); + router.push('/message/2'); + await waitForRouter(); + router.push('/message/3'); + await waitForRouter(); + + router.go(-2); + await waitForRouter(); + expect(router.currentRoute.value.path).toBe('/message/1'); + + router.push('/settings'); + await waitForRouter(); + + expect(leftPages).toEqual(['1']); + }); + + it('should run the leave guard of the page navigated forward to with router.go()', async () => { + const leftPages: string[] = []; + const router = createAppRouter(createGuardedDetail(leftPages)); + await mountApp(router); + + router.push('/message/1'); + await waitForRouter(); + router.push('/message/2'); + await waitForRouter(); + router.push('/message/3'); + await waitForRouter(); + + router.go(-2); + await waitForRouter(); + router.go(2); + await waitForRouter(); + expect(router.currentRoute.value.path).toBe('/message/3'); + + router.push('/settings'); + await waitForRouter(); + + expect(leftPages).toEqual(['3']); + }); +});