记一次统计用户浏览网站的时长

项目需求:统计用户浏览该网站的时长
初始方案:只需要在根入口的的组件被销毁的时候通过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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值