vue怎么实现点击获取现在时间,然后点击暂停按钮暂停在获取时间并计算时长
1条回答 默认 最新
雪浸梅香 2023-06-06 11:59关注在Vue中,获取现在的时间可以使用JavaScript的Date对象,计算时长可以使用Date对象的getTime()方法取得时间戳,然后计算两个时间戳之间的时间差。
以下是一个简单的示例代码,实现了获取当前时间和点击按钮计算时长的功能:
<template> <div> <p>当前时间:{{ currentTime }}</p> <button @click="calculateDuration">计算时长</button> <p>时长:{{ duration }}</p> </div> </template> <script> export default { data() { return { currentTime: "", // 当前时间 startTimeStamp: 0, // 开始时间戳 duration: 0, // 时长 }; }, methods: { // 获取当前时间 getCurrentTime() { const now = new Date(); const year = now.getFullYear(); const month = this.formatTime(now.getMonth() + 1); const date = this.formatTime(now.getDate()); const hour = this.formatTime(now.getHours()); const minute = this.formatTime(now.getMinutes()); const second = this.formatTime(now.getSeconds()); this.currentTime = `${year}-${month}-${date} ${hour}:${minute}:${second}`; }, // 格式化时间 formatTime(time) { return time < 10 ? "0" + time : time; }, // 点击按钮计算时长 calculateDuration() { const endTimeStamp = new Date().getTime(); // 结束时间戳 this.duration = (endTimeStamp - this.startTimeStamp) / 1000; // 计算时长,单位为秒 }, }, mounted() { this.getCurrentTime(); // 组件挂载时获取当前时间 this.startTimeStamp = new Date().getTime(); // 记录开始时间戳 }, }; </script>在上面的示例中,getCurrentTime()方法使用Date对象获取当前时间并格式化输出到页面中。
在mounted()方法中,初始化页面时获取当前时间并记录开始时间戳。
点击按钮时,调用calculateDuration()方法,计算时长并显示在页面上。其中,计算时长的方法用到了Date对象的getTime()方法,该方法返回时间戳,单位为毫秒。最后将得到的时长转换为秒并显示在页面上。
解决 无用评论 打赏 举报