uni-app vuex全局计时

功能需求,在A页面进入时候开始计时中间会去到B页面查看数据,但是并没有销毁当前页面,所以计时一直在,直到在B页面提交数据,才结束计时

javascript 复制代码
在根文件夹创建 store文件夹,同时创建index.js文件

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
	// 开始时间
	// startTime: null,
	// 结束时间
	endTime: null,
	// 计时器对象
	timerot: null,
	// 计时时间
	time: 0 
  },
  mutations: {
	// 设置计时器对象
	setTimer(state, timerot) {
	  state.timerot = timerot
	},
	// 设置计时时间
	setTime(state, time) {
	  state.time = time
	},
	// 停止计时器
	stopTimer(state) {
	  clearInterval(state.timerot)
	  state.timerot = null
	},
	// 重置计时时间
	resetTime(state) {
	  state.time = 0
	}
	
  },
  actions: {
  }
})

export default store

在main.js引入

javascript 复制代码
import store from './store'

App.mpType = 'app'

const app = new Vue({
	store,
	...App
})
app.$mount()

在需要计时的页面引入

javascript 复制代码
<template>
	<text class="titlename">{{ formatTime }}</text>
</template>

<script>
import { mapMutations } from 'vuex'

export default {
		beforeDestroy() {
		    this.stopTimer()
		},
		onLoad() {
			// 计时开始
			this.startTimer()
		},
		methods: {
			// 顶部计时
			// 开始计时
			startTimer() {
			    this.resetTime()
			    this.setTimer(setInterval(() => {
					this.setTime(this.time + 1)
			    }, 1000))
			},
			...mapMutations(['setTimer', 'setTime', 'resetTime']),
		},
		computed: {
			 // 格式化计时时间
			formatTime() {
				const minutes = Math.floor(this.time / 60) < 10 ? "0" + Math.floor(this.time / 60) : Math.floor(this.time / 60)
				const seconds = this.time % 60
				return `${minutes}:${seconds.toString().padStart(2, '0')}`
			},
		}
	}
</script>

在需要结束的页面调用

javascript 复制代码
<template>
	<view class="oo_item sure_i_want_to_exit out_flex_cc" 
	@click="ConfirmSubmissionOfPapers"
	>
		确认提交
	</view>
</template>


<script>
import { mapMutations } from 'vuex'

export default {
		methods: {
			// 确认提交
			ConfirmSubmissionOfPapers(){
				// 结束计时
				this.stopTimer()
				// 在这里可以获取到计时时间 time,并进行后续操作
				const time = this.time
				const minutes = Math.floor(time / 60)
				const seconds = time % 60
				console.log("结束时间的整数",time);
				console.log("结束时间",`${minutes}:${seconds.toString().padStart(2, '0')}`);
				
			},
			...mapMutations(['stopTimer']), // 结束计时
		},

	}
</script>
相关推荐
Setsuna_F_Seiei5 小时前
前端的 AI 学习之路 01 之 Agent API 调用 - 和 Agent 的基础对话
前端·人工智能·ai编程
threerocks6 小时前
AI 原生软件开发生命周期手册 - 如何借助 AI,逐阶段改造软件开发生命周期
前端·javascript·后端
徐小夕6 小时前
3分钟从想法到Agent上线:我们开源了一款AI可视化工作流“IDE”
前端·算法·github
why技术8 小时前
eli5,我觉得这个全网在吹的技能,使用体验真的很一般啊。
前端·人工智能·后端
excel8 小时前
记录升级 nuxt3 到 nuxt4 记录
前端
剑胆琴心静水深流8 小时前
全栈之路6---web集成与呈现
前端·vue.js·spring boot·分布式·spring·前端框架·npm
前端snow8 小时前
ai agent -- Memory汇总
前端
ITresearchGuest9 小时前
AI 焦虑下,前端该何去何从
前端·人工智能
Codiggerworld9 小时前
Chrome DevTools 隐藏神技:这 5 个调试技巧你可能从来没用过
前端·chrome·chrome devtools
旋生万物9 小时前
【终极实战】用Python从零“生成“一个宇宙:螺旋干涉模型的代码实现
开发语言·前端·人工智能·react.js·php·wpf