uni-app:实现时钟自走(动态时钟效果)

效果

核心代码

  • 使用钩子函数 mounted(),设置定时器,是指每秒都要去执行时间的获取,以至于实现时间自走的效果

mounted() {

this.updateTime(); // 初始化时间

setInterval(this.updateTime, 1000); // 每秒更新时间

},

  • 自定义方法updateTime去获取当前时间,并设置数据

updateTime() {

const date = new Date();

const hours = date.getHours().toString().padStart(2, '0');

const minutes = date.getMinutes().toString().padStart(2, '0');

const seconds = date.getSeconds().toString().padStart(2, '0');

this.currentTime = `{hours}:{minutes}:${seconds}`;

}

完整代码

html 复制代码
<template>
  <view class="time-container">
    <view>{{ currentTime }}</view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      currentTime: '' // 当前时间
    };
  },
  mounted() {
    this.updateTime(); // 初始化时间
    setInterval(this.updateTime, 1000); // 每秒更新时间
  },
  methods: {
    updateTime() {
      const date = new Date();
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      this.currentTime = `${hours}:${minutes}:${seconds}`; 
    }
  }
};
</script>
<style>
.time-container {
  text-align: center;
  font-size: 24px;
}

</style>
相关推荐
奔跑的web.2 小时前
UniApp 路由导航守
前端·javascript·uni-app
特立独行的猫a3 小时前
主要跨端开发框架对比:Flutter、RN、KMP、Uniapp、Cordova,谁是未来主流?
flutter·uni-app·uniapp·rn·kmp·kuikly
万物得其道者成14 小时前
UniApp 多端滑块验证码插件 zxj-slide-verify 实用指南
uni-app
蓝帆傲亦16 小时前
支付宝小程序性能暴增秘籍:UniApp项目极限优化全攻略
小程序·uni-app
2501_916008891 天前
深入解析iOS机审4.3原理与混淆实战方法
android·java·开发语言·ios·小程序·uni-app·iphone
QT.qtqtqtqtqt1 天前
uni-app小程序前端开发笔记(更新中)
前端·笔记·小程序·uni-app
喵喵虫2 天前
uniapp修改封装组件失败 styleIsolation
uni-app
游戏开发爱好者82 天前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 天前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 天前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone