如果组件在 Nativescript Vue 中处于非活动状态,如何停止代码执行

how to stop code execution if the component is inactive in Nativescript Vue

我的应用程序应该每 5 秒发送一次关于设备的数据,但是如果我最小化应用程序并重新打开它,或者如果我只是返回页面并返回,代码会继续 运行 甚至在后台。当我再次打开应用程序时,发送数据的功能叠加在一个已经工作的功能上,数据离开的频率是原来的两倍,所以你可以无限期地创建一个功能

如何解决这个问题?

我的方法:

sendDeviceInfo(){
                console.log("1111");
                axios.post('', {
                    device: DeviceInfo.systemManufacturer() + ' ' +DeviceInfo.deviceName(),
                    deviceId: DeviceInfo.deviceId(),
                    appId: DeviceInfo.appVersion(),
                    email: this.email,
                    battery: DeviceInfo.batteryLevel(),
                    batteryCharging: DeviceInfo.isBatteryCharging() === true ? 1 : 0
                });
            }

并挂载:

this.sendDeviceInfo();
setInterval(this.sendDeviceInfo, 5000);

您需要清除组件销毁的时间间隔。 setInterval returns 您可以用来清除它的参考。

data: () => ({
    ...yourDataStuff,
    sendDeviceInfoInterval: null
}),

mounted() {
    this.sendDeviceInfoInterval = setInterval(this.sendDeviceInfo, 5000);
},

beforeDestroy() {
    clearInterval(this.sendDeviceInfoInterval);
}