Ionic 5, Vue 3 - How to use Ionic lifecycle hooks inside setup()?

2.3k Views Asked by At

The Ionic documentation describes how to use the Ionic lifecycle methods like ionViewWillEnter, ionViewDidEnter etc. inside Vue method.

https://ionicframework.com/docs/vue/lifecycle

I'm looking for a way to access them inside the new Vue 3 setup() method so that I can able to access the properties defined there. Is it something possible?

export default defineComponent({
   ...
   setup(){
      const list = ref([]);

      // I need something like this
      const ionViewDidEnter = () => {
         list.value.push(...['some', 'array', 'here']);
      },

      return {
         list,
         ionViewDidEnter
      };
   }
});
3

There are 3 best solutions below

0
On BEST ANSWER

This is now possible in a composition API style since this PR was merged

https://github.com/ionic-team/ionic-framework/pull/22970

export default defineComponent({
  ...,
  components: { IonPage },
  setup() {
    onIonViewDidEnter(() => {
      console.log('ionViewDidEnter!');
    });
  }
});
1
On

Unfortunately no, at least not yet, since the code firing the events is specifically looking for the lifecycle events to be registered as part of the component methods. Luckily I've submitted a PR which is going to fix this and allow you to define them the same way you would define mounted or any other Vue hooks.

I will make sure to add tests that cover the composition API scenario as well.

https://github.com/ionic-team/ionic-framework/pull/22241

Meaning that you'd be able to do it this way:

export default defineComponent({
   ...
   ionViewDidEnter() {
     ...
   },
   setup(){
     ...
   }
});
0
On

Just to add to what Mark Beech said, you will have to import onIonViewDidEnter

import { onIonViewDidEnter } from '@ionic/vue';

export default defineComponent({
   ...
   ionViewDidEnter() {
      console.log('Hompage');
   },
   setup(){
     ...
   }
});