手机锁屏vue页面js倒计时停止怎么办

在Vue页面中实现手机锁屏后倒计时停止的功能,可以通过监听visibilitychange事件来判断页面是否在可见状态。如果页面不可见(即锁屏状态),则清除倒计时;如果页面可见,则重新开始倒计时。

以下是一个简单的示例代码:

<template>
  <div>
    <p>倒计时: {{ countdown }}</p>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      countdown: 60, // 假设倒计时60秒
      timer: null,
      isPageVisible: true, // 页面是否可见的标志
    };
  },
  created() {
    this.startCountdown();
    document.addEventListener('visibilitychange', this.handleVisibilityChange);
  },
  beforeDestroy() {
    this.clearCountdown();
    document.removeEventListener('visibilitychange', this.handleVisibilityChange);
  },
  methods: {
    startCountdown() {
      if (this.timer) return;
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          this.clearCountdown();
        }
      }, 1000);
    },
    clearCountdown() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    handleVisibilityChange() {
      if (document.visibilityState === 'visible' && this.isPageVisible === false) {
        this.startCountdown();
      } else if (document.visibilityState === 'hidden') {
        this.clearCountdown();
      }
      this.isPageVisible = document.visibilityState === 'visible';
    },
  },
};
</script>

在这个示例中,当组件被创建时,倒计时开始,同时监听visibilitychange事件。当页面变为不可见时(锁屏),清除倒计时;当页面再次变为可见时,倒计时重新开始。组件销毁前,清除计时器和事件监听器,以防止内存泄露。

Vue3中,如果你想要创建一个页面刷新后依然保持倒计时功能的倒计时组件,你需要做以下几个步骤: 1. **状态管理**:将倒计时的状态(比如剩余时间)存储在一个响应式的变量中,可以使用Vuex或者自定义 reactive 对象来管理。这样,无论组件是否被重新渲染,状态都能持久。 ```javascript // 使用Vuex示例 import { createStore } from 'vuex'; const store = createStore({ state: { countdown: null, }, mutations: { setCountdown(state, value) { state.countdown = value; }, }, }); export default store; ``` 2. **组件内部处理**:在组件的`beforeCreate`钩子或者生命周期钩子`beforeMount`中设置初始的倒计时,并在适当的地方更新这个状态。 ```vue <template> <div v-if=countdown> {{ countdown }} </div> </template> <script> import { mapState } from 'vuex'; export default { data() { return {}; }, computed: { ...mapState(['countdown']), }, beforeCreate() { // 初始化倒计时,在这里设置或从服务获取 this.getCountdown(); }, methods: { getCountdown() { // 获取倒计时并保存到store this.$store.commit('setCountdown', getInitialCountdown()); }, }, }; </script> ``` 3. **路由跳转与守卫**:如果需要在路由切换时不丢失倒计时,你可以使用路由导航守卫`beforeRouteUpdate`或`beforeEach`来检测路由变化,并在必要时更新倒计时。 ```javascript router.beforeEach((to, from, next) => { if (from.fullPath !== to.fullPath && to.name !== 'not-countdown') { this.getCountdown(); // 更新倒计时 } next(); }); ``` 这样,当页面刷新或路由改变时,只要不是特殊处理的路由,倒计时组件就会自动重新计算剩余时间并显示出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值