在uniapp中实现扫码功能,并显示结果与时间

<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>

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值