<template>
<!-- 现在的时间 -->
<view class="container">
<view class="time">{{time}}</view>
<button @click="scan">扫码</button>
</view>
<view class="result-area">
<text v-if="scanResult">{{ scanResult }}</text> </view>
</template>
<script>
export default {
data() {
return {
time: '',
};
},
mounted() {
var timer = setInterval(() => {
this.getNowTime();
}, 1000); //1000ms更新一次时间
},
// 组件销毁时关闭定时器
beforeDestroy() {
clearInterval(timer);
},
methods: {
scan() {
uni.scanCode({
success: (res) => {
this.scanResult = res.result;
},
fail: (err) => {
console.error('扫码失败:', err);
}
});
},
// 获取当前时间,包括年月日时分秒
getNowTime() {
var date = new Date();
// 年,使用 getFullYear() 获取四位数字的年份
var year = date.getFullYear();
// 月,getMonth() 返回的是 0 到 11,需加 1 得到实际月份
var month = date.getMonth() + 1;
// 日
var day = date.getDate();
// 时
var hour = date.getHours();
// 分
var minute = date.getMinutes();
// 秒
var second = date.getSeconds();
var time = year + '-' + this.addZero(month) + '-' + this.addZero(day) +' ' + this.addZero(hour) + ':' + this.addZero(minute) + ':' + this.addZero(second);
this.time = time;
},
addZero(s) {
return s < 10? ('0' + s) : s; // 小于 10 的数字前面拼接上 0 字符串
},
},
};
</script>
<style scoped>
.container {
height: 90rpx;
border: 1rpx solid #fff;
display: flex;
align-items: center;
background-color: #dafde6;
right: 0;
left:0;
}
.time {
margin-left: 56rpx;
color: #02a53c;
font-size: 30rpx;
font-weight: 500;
}
button {
position: absolute;
bottom: 0;
right: 0;
left: 0;
background-color: #4CAF50;
color: white;
}
.result-area{
color: blue;
background-color: blanchedalmond;
height: 200rpx;
left: 0;
right: 0;
}
</style>
03-18
1541
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-31