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>
相关推荐
Rysxt_11 小时前
UniApp五大UI框架与uni-ui核心区别对比
uni-app·uni-ui
2501_9159184112 小时前
HTTPS 代理失效,启用双向认证(mTLS)的 iOS 应用网络怎么抓包调试
android·网络·ios·小程序·https·uni-app·iphone
2501_9151063215 小时前
混合应用(Hybrid)安全加固,不依赖源码对成品 IPA 混淆
android·安全·小程序·https·uni-app·iphone·webview
00后程序员张16 小时前
无需越狱,来对 iOS 设备进行调试、管理与分析
android·ios·小程序·https·uni-app·iphone·webview
芒果大胖砸16 小时前
uniapp当中如何实现长按复制功能并且能够自由选择内容
开发语言·javascript·uni-app
00后程序员张16 小时前
在 iOS 上架中如何批量方便快捷管理 Bundle ID
android·ios·小程序·https·uni-app·iphone·webview
换日线°16 小时前
uni-app对接腾讯即时通讯 IM
前端·uni-app
咚咚?16 小时前
uniapp [JS Framework] 当前运行的基座不包含原生插件[xxxx],请在manifest中配置该插件,重新制作包括该原生插件的自定义运行基座
开发语言·javascript·uni-app
木子啊16 小时前
Uni-app生命周期:执行顺序与避坑指南
前端·javascript·uni-app
快起来搬砖了16 小时前
UniApp 全端兼容 OSS 视频上传实现方案
小程序·uni-app·app·h5·文件上传·oss文件上传