封装一个计时器,记录页面的停留时间

231 阅读1分钟

在页面加载时初始化计时器,页面结束时取值。

效果如图:

下面是uniapp的代码示例:

<template>
	<view class="aaaacc">
		<view class="aaa">
			{{time}}
		</view>
	</view>
</template>

<script>
	// 计时器
	function time_s() {
		setTimeout(()=> {
			this.time = ++this.time
			time_s.call(this)
		}, 1000);
	}
	// import downloadFile from "@/util/downloadFile.js";
	export default {
		data() {
			return {
				time: 1
			}
		},
		onUnload() {
			console.log('页面停留时间', this.time)
		},
		onLoad() {
			time_s.call(this)
		},
		onHide() {
		},
		methods: {
		}
	}
</script>

<style>
	.aaa {
		height: 120rpx;
		line-height: 120rpx;
		margin: 20rpx;
		background-color: #00C7DD;
		text-align: center;
		color: white;
	}

	.aaaacc {
		margin-top: 400rpx;
	}
</style>