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>
相关推荐
fakaifa4 小时前
【高级版】沃德政务招商系统源码+uniapp小程序
小程序·uni-app·源码下载·沃德政务招商系统·招商系统源码
weixin_446938874 小时前
uniapp vue-i18n如何使用
前端·vue.js·uni-app
有来技术4 小时前
UniApp 自定义导航栏适配指南:微信小程序胶囊遮挡、H5 与 App 全端通用方案
微信小程序·uni-app
卷Java13 小时前
违规通知功能修改说明
java·数据库·微信小程序·uni-app
卷Java1 天前
用户权限控制功能实现说明
java·服务器·开发语言·数据库·servlet·微信小程序·uni-app
王佳斌2 天前
sass变量默认
uni-app
二饭2 天前
uniapp与webview通信
uni-app
2501_915909062 天前
iOS 抓包工具有哪些?实战对比、场景分工与开发者排查流程
android·开发语言·ios·小程序·uni-app·php·iphone
2501_915918413 天前
iOS 框架全解析,原生框架与跨平台框架对比、开发应用打包与 App Store 上架实战经验
android·ios·小程序·https·uni-app·iphone·webview
街尾杂货店&3 天前
cssword属性
uni-app