项目需求:统计用户浏览该网站的时长
初始方案:只需要在根入口的的组件被销毁的时候通过axios请求接口,提交时间给后台,在实际测试的时候发现,请求还没发送过去就被取消,使用axios请求,是异步请求,导致页面卸载时,请求被取消。
解决方案:换成同步事件
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
import server_url from '../static/server.js'
import axios from "axios";
import { exists, constants } from "fs";
export default {
data() {
return {
openTime: "",
account: "",
startDate: performance.now() // 获取当前时间的毫秒数
};
},
mounted() {
const that = this;
this.account = this.$route.query.account;
console.log(that.startDate, "that.that.startDate",this.account);
//初始原因使用axios请求,是异步请求,导致页面卸载时,请求被取消
window.onbeforeunload = function(e) {
that.openTime = (performance.now() - that.startDate) / 1000;
console.log(that.openTime, "that.openTime");
var data = {
account: that.account,
date: that.changeDateTime(new Date()),
openTime: parseInt(that.openTime)
};
//发送同步请求
var oReq = new XMLHttpRequest();
oReq.open(
"POST",
`${server_url}/putuan/v1/dealer/browse/time`,
false
); // 同步请求
oReq.setRequestHeader("Content-type", "application/json");
oReq.send(JSON.stringify(data));
};
},
created() {},
methods: {
changeDateTime(time) {
const that = this;
var date = new Date(time);
var month = that.addZore(date.getMonth() + 1);
var time =
that.addZore(date.getHours()) +
":" +
that.addZore(date.getMinutes()) +
":" +
that.addZore(date.getSeconds());
var dateStr =
date.getFullYear() +
"-" +
month +
"-" +
that.addZore(date.getDate()) +
" " +
time;
console.log(dateStr, "date");
return dateStr;
},
addZore(value) {
return ("0" + value).slice(-2);
}
}
};
</script>