如何在Active Ionic Vue时每次在安装上调用函数?

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

我在 vue 中使用 ionic。有一个标签栏,它有子标签,当我更改该栏时,它调用组件的已安装函数,但它仅在第一次调用该函数,其他时间它显示以前的数据。

这里是标签栏

<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>

这是子选项卡 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>

标签组件

<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 组件

<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>

您正在寻找 ionic lifecycle ionViewWillEnter,它会在用户每次进入页面时触发:

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