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>
相关推荐
2501_915106327 小时前
App Store 软件上架全流程详解,iOS 应用发布步骤、uni-app 打包上传与审核要点完整指南
android·ios·小程序·https·uni-app·iphone·webview
快起来搬砖了7 小时前
实现一个优雅的城市选择器组件 - Uniapp实战
开发语言·javascript·uni-app
数学分析分析什么?7 小时前
Uniapp中使用renderjs实现OpenLayers+天地图的展示与操作
uni-app·openlayers·天地图·renderjs
海绵宝宝不喜欢侬7 小时前
UniApp微信小程序-实现蓝牙功能
微信小程序·uni-app
Python大数据分析10 小时前
uniapp微信小程序商品列表数据分页+本地缓存+下拉刷新+图片懒加载
缓存·微信小程序·uni-app
机构师10 小时前
<uniapp><指针组件>基于uniapp,编写一个自定义箭头指针组件
javascript·uni-app·vue·html
小白_ysf10 小时前
uniapp和vue3项目中引入echarts 、lime-echart(微信小程序、H5等)
微信小程序·uni-app·echarts·h5·lime-echart
imHere·10 小时前
UniApp 分包异步化配置及组件引用解决方案
微信小程序·uni-app·分包
2501_9160137413 小时前
App 上架全流程指南,iOS App 上架步骤、App Store 应用发布流程、uni-app 打包上传与审核要点详解
android·ios·小程序·https·uni-app·iphone·webview
0x00013 小时前
Uniapp - 自定义 Tabbar 实现
前端·uni-app