Skip to content

fix: @vueuse/head doesn't function properly with ionic #6

@callumacrae

Description

@callumacrae

🐛 The bug

Hey!

Not using this project, but had a problem on another project I think you'll run into so figured I'd make you aware as it's not immediately obvious

https://ionicframework.com/docs/vue/lifecycle#how-ionic-framework-handles-the-life-of-a-page

The way ionic handles the lifecycle of a page is very different to how vue does it, and as a consequence of this, the onBeforeMount hook isn't always called when you'd expect it to be.

To replicate, go to the stackblitz below, inspect the <title> of the ionic app, and click between the first and second tabs a few times. You'll notice that the title stops updating. This is because the old tab still exists in the dom.

It looks like you can probably work around this by importing injectHead from @vueuse/head, onIonViewWillLeave from @ionic/vue and creating your own useHead function that handles the teardown (and setting up again, potentially) with the correct hook. I haven't actually tried this though as I gave up and went back to doing everything manually.

export const useHead = (obj: MaybeRef<HeadObject>) => {
  const headObj = ref(obj) as Ref<HeadObjectPlain>
  const head = injectHead()

  head.addHeadObjs(headObj)

  if (IS_BROWSER) {
    watchEffect(() => {
      head.updateDOM()
    })

    onIonViewDidEnter(() => {
      head.addHeadObjs(headObj)
      head.updateDOM()
    })

    onIonViewWillLeave(() => {
      head.removeHeadObjs(headObj)
      head.updateDOM()
    })
  }
}

Something like this! The onIonViewDidEnter is required for when a user goes back to a page which has been fake-unmounted by ionic. The addHeadObjs can probably be deduplicated but as I said, I haven't tested this!

(vue-meta has the same problem)

🛠️ To reproduce

https://stackblitz.com/edit/github-xdesgf-6vva3r?file=pages%2Ftabs.vue,pages%2Ftabs%2Ftab1.vue,pages%2Ftabs%2Ftab2.vue,pages%2Ftabs%2Ftab3.vue

🌈 Expected behaviour

ℹ️ Additional context

No response

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions