How to call function on mounted every time when tab is active ionic vue?

Issue

I am using ionic with vue. there is tab bar which has child tab when i change that bar it calls mounted function of component but it calls that function only first time for all other time it shows previous data.

here is tab bar

<ion-tabs>
      <ion-tab-bar>
        <ion-tab-button tab="tab1" href="/tabs/tab1" class="notification-icon-button">
          <ion-badge
            class="notification-badge"
            style="background-color: #d91707; size: 10px"
            v-if="notification_count> 0"
          >{{ notification_count}}</ion-badge>
          <ion-icon :icon="globe" />
          <ion-label>Notifications</ion-label>
        </ion-tab-button>

        <ion-tab-button tab="tab2" href="/tabs/tab2" ref="get" @click="hel" v-if="role_id == 9">
          <ion-icon :icon="ellipse" />
          <ion-label>Workers</ion-label>
        </ion-tab-button>

        <ion-tab-button tab="tab3" href="/tabs/tab3" v-if="role_id == 9">
          <ion-icon :icon="square" />
          <ion-label>RHM</ion-label>
        </ion-tab-button>
            <ion-tab-button tab="tab4" href="/tabs/tab4" v-if="role_id == 10">
          <ion-icon :icon="square" />
          <ion-label>Weight</ion-label>
        </ion-tab-button>
      </ion-tab-bar>
    </ion-tabs>

here is child tab Tab2

<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-title>My Wrokers</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content :fullscreen="true">
      <ion-header collapse="condense">
        <ion-toolbar>
          <ion-title size="large">My Workers</ion-title>
        </ion-toolbar>
      </ion-header>
      <ion-list>
    <ion-item v-for="(worker, index) in this.workers" :key="index" @click="() => router.push(`/staff/${worker.id}/worker`)">
      <ion-label
        text-wrap>{{ worker.id }} - {{ worker.name }}
      </ion-label>
    </ion-item>
  </ion-list>
    </ion-content>
  </ion-page>
</template>

<script >
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
   IonItem, IonList, IonLabel,
} from "@ionic/vue";
import { TokenService } from '@/services/token.service';
import ApiService from '@/services/api.service';
import { useRouter } from 'vue-router';
export default {
  name: "Tab2",
  data() {
    return {
      workers: "",
    };
  },
  components: { IonHeader, IonToolbar, IonTitle, IonContent, IonPage, IonItem, IonList, IonLabel, },
  methods: {
    getBossWorkers: function () {
      const boss_id = TokenService.getUserInfo().id;

      return ApiService.get(`/api/gangBoss/get-boss-workers/${boss_id}`).then(
        (response) => {
          this.workers = response.data;

        }
      );
    },
  },
  setup() {
      const router = useRouter();
      return { router };
    },
  mounted() {

    this.getBossWorkers();
  },
};
</script>
<style scoped>
ion-list ion-item {
  background-color: #F0F8FF;

    /* margin-top: 7px; */
  margin-bottom: 0px;
}
</style>

tabs component

<template>
  <ion-page>
    <ion-tabs>
      <ion-tab-bar>
        <ion-tab-button tab="tab1" href="/tabs/tab1" class="notification-icon-button">
          <ion-badge
            class="notification-badge"
            style="background-color: #d91707; size: 10px"
            v-if="notification_count> 0"
          >{{ notification_count}}</ion-badge>
          <ion-icon :icon="globe" />
          <ion-label>Notifications</ion-label>
        </ion-tab-button>

        <ion-tab-button tab="tab2" href="/tabs/tab2" ref="get" @click="hel" v-if="role_id == 9">
          <ion-icon :icon="ellipse" />
          <ion-label>Workers</ion-label>
        </ion-tab-button>

        <ion-tab-button tab="tab3" href="/tabs/tab3" v-if="role_id == 9">
          <ion-icon :icon="square" />
          <ion-label>RHM</ion-label>
        </ion-tab-button>
            <ion-tab-button tab="tab4" href="/tabs/tab4" v-if="role_id == 10">
          <ion-icon :icon="square" />
          <ion-label>Weight</ion-label>
        </ion-tab-button>
      </ion-tab-bar>
    </ion-tabs>
  </ion-page>
</template>

<script >
import {
  IonTabBar,
  IonTabButton,
  IonTabs,
  IonLabel,
  IonIcon,
  IonPage,
} from "@ionic/vue";
import { ellipse, square, triangle, globe } from "ionicons/icons";
import { TokenService } from "@/services/token.service";
import Pusher from "pusher-js";

import { mapGetters } from "vuex";
import ApiService from "@/services/api.service";
import { Plugins } from "@capacitor/core";
const { App ,Network} = Plugins;

export default {
  name: "Tabs",
  components: { IonLabel, IonTabs, IonTabBar, IonTabButton, IonIcon, IonPage },
  setup() {
    return {
      ellipse,
      square,
      triangle,
      globe,
      TokenService,
    };
  },
  data() {
    return {
      notification: {},
      role_id: TokenService.getUserInfo().role_id,

      notification_count: 0,
    };
  },
  computed: {
    ...mapGetters("auth", ["getNotification"]),
  },
  methods: {
    hel:function()
    {
       console.log(this.$refs.get)
    },
    //   getLocation: function () {
    //     const geolocation = new GeolocationService.Geolocation();

    //    let watch = geolocation.watchPosition();
    // watch.subscribe((data) => {

    //  // data can be a set of coordinates, or an error (if an error occurred).
    //  // data.coords.latitude
    //  // data.coords.

    //  this.subscribe(data.coords.longitude,data.coords.latitude)
    // });

    //   },
    subscribe: function (longitude, latitude) {
      let pusher = new Pusher("28e0e5bc1814e859e3b6", {
        cluster: "mt1",
        authEndpoint: "http://localhost:8000/api/pusher/auth",
        headers: {
          "Access-Control-Allow-Origin": "*",
        },
      });
      let channel = pusher.subscribe("private-location-11");

      channel.bind("pusher:subscription_succeeded", function () {
        // for example:
        channel.trigger("client-location_changed", {
          data: {
            longitude: longitude,
            latitude: latitude,
          },
        });
      });
      //   pusher.bind('location_changed', data => {
      //  console.log(data)
      //   channel.trigger('location_changed', { your: data });
      //   })
    },
    notiAPI() {
      ApiService.get("/api/staff/get-notifications").then((res) => {
        this.notification_count = res.data.length;
      });
    },
    fetchNotifications() {
      this.$store.subscribe((getNotification, state) => {
        console.log(state);
        console.log(getNotification.payload);
        this.notiAPI();
      });
    },
  },
 async created() {
    this.notiAPI();
    this.fetchNotifications();
    App.addListener("appStateChange", (state) => {
      console.log("state");
      if (state.isActive == false) {
        this.fetchNotifications();
      }
    });
     let status = await Network.getStatus();
    if (status.connected) {
       this.fetchNotifications();
    }

    Network.addListener("networkStatusChange", async (status) => {
      if (status.connected) {
       this.fetchNotifications();
      }
    });
  },
};
</script>


tab2 component

<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-title>My Wrokers</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content :fullscreen="true">
      <ion-header collapse="condense">
        <ion-toolbar>
          <ion-title size="large">My Workers</ion-title>
        </ion-toolbar>
      </ion-header>
      <ion-list>
    <ion-item v-for="(worker, index) in this.workers" :key="index" @click="() => router.push(`/staff/${worker.id}/worker`)">
      <ion-label
        text-wrap>{{ worker.id }} - {{ worker.name }}
      </ion-label>
    </ion-item>
  </ion-list>
    </ion-content>
  </ion-page>
</template>

<script >
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
   IonItem, IonList, IonLabel,
} from "@ionic/vue";
import { TokenService } from '@/services/token.service';
import ApiService from '@/services/api.service';
import { useRouter } from 'vue-router';
import {defineComponent} from 'vue';
export default defineComponent({
  name: "Tab2",
  data() {
    return {
      workers: "",
    };
  },
  components: { IonHeader, IonToolbar, IonTitle, IonContent, IonPage, IonItem, IonList, IonLabel, },
  methods: {
    getBossWorkers: function () {
      const boss_id = TokenService.getUserInfo().id;

      return ApiService.get(`/api/gangBoss/get-boss-workers/${boss_id}`).then(
        (response) => {
          this.workers = response.data;

        }
      );
    },
  },
  setup() {
    ionViewDidEnter(() => {
      console.log('Home page did enter');
    });

      const router = useRouter();
      return { router };
    },
  mounted() {

    this.getBossWorkers();
  },


});
</script>
<style scoped>
ion-list ion-item {
  background-color: #F0F8FF;

    /* margin-top: 7px; */
  margin-bottom: 0px;
}
</style>

Solution

You are looking for ionic lifecycle ionViewWillEnter, it will fire every time user enters the page:

setup() {
  onIonViewWillEnter(() => {
    console.log('Entered tab!');
  });
}

Answered By – AJT82

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published