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>
相关推荐
云起SAAS1 天前
私域直播系统UniApp源码 多商户商城+直播带货 微信小程序+H5+安卓iOS
android·微信小程序·uni-app·私域直播系统
专科3年的修炼3 天前
uni-app移动应用开发第四章
开发语言·javascript·uni-app
q5507071773 天前
uniapp/uniappx实现原生图片编辑涂鸦、贴图、滤镜、旋转、裁剪等
uni-app
计算机学姐4 天前
基于微信小程序的校园失物招领管理系统【uniapp+springboot+vue】
java·vue.js·spring boot·mysql·信息可视化·微信小程序·uni-app
2501_915921434 天前
HTTPS前端劫持 新一代流量劫持解决方案
前端·网络协议·ios·小程序·https·uni-app·iphone
爱怪笑的小杰杰4 天前
优化 UniApp 日历组件的多语言切换:告别 setLocale 引起的 App 重启
java·前端·uni-app
计算机学姐4 天前
基于微信小程序的宠物服务系统【uniapp+springboot+vue】
java·vue.js·spring boot·mysql·微信小程序·uni-app·宠物
2501_915909064 天前
iOS应用签名的三种方法全解析:从官方到第三方工具
android·ios·小程序·https·uni-app·iphone·webview
心中无石马5 天前
uniapp引入tailwindcss4.x
前端·css·uni-app
fix一个write十个5 天前
【uniApp开发】微信小程序 web-view 内嵌 H5 跳转支付踩坑实录
微信小程序·uni-app