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>
相关推荐
勇敢di牛牛1 分钟前
Vue+mockjs+Axios 案例实践
前端·javascript·vue.js
Sheldon一蓑烟雨任平生11 分钟前
Vue3 Class 与 Style 绑定
vue.js·vue3·class与style绑定·绑定class·绑定style·vue3绑定class·vue3绑定style
詩句☾⋆᭄南笙11 分钟前
HTML列表、表格和表单
服务器·前端·html·表格·列表·表单
IT_陈寒24 分钟前
Python性能翻倍的5个冷门技巧:从GIL逃逸到内存视图的实战优化指南
前端·人工智能·后端
南城巷陌28 分钟前
错误边界:用componentDidCatch筑起React崩溃防火墙
前端·react.js·前端框架
FinClip34 分钟前
OpenAI推出Apps SDK,你的企业App跟上了吗?
前端·app·openai
馨谙39 分钟前
Linux中的管道与重定向:深入理解两者的本质区别
前端·chrome
2501_9159214342 分钟前
iOS 应用加固与苹果软件混淆全解析 IPA 文件防反编译、混淆加密与无源码加固策略
android·macos·ios·小程序·uni-app·cocoa·iphone
夏天想1 小时前
复制了一个vue的项目然后再这个基础上修改。可是通过npm run dev运行之前的老项目,发现运行的竟然是拷贝后的项目。为什么会这样?
前端·vue.js·npm
@大迁世界1 小时前
这个 CSS 特性,可能终结样式冲突
前端·css