vue 实现时钟

您所在的位置:网站首页 前端翻页时钟 vue 实现时钟

vue 实现时钟

2024-07-14 13:49| 来源: 网络整理| 查看: 265

采用定时器来获取最新的时间,通过Date的方法获取年份、月份、日期、星期以及当前时间,用来拼装时钟,然后使用生命周期函数create来创建定时器,是时钟每隔一秒钟发生一次变化,达到时钟在走的效果,同时在beforeDestroy函数中清除定时器

App.vue如下:

const days = ['天', '一', '二', '三', '四', '五', '六']; // 星期数组 var icnow = new Date(); // 初始化时间 var interval; // 定义全局定时器,用于清除定时器 export default { name: 'app', data() { return { year: icnow.getFullYear(), month: icnow.getMonth() + 1, date: icnow.getDate(), day: days[icnow.getDay() - 1], time: icnow.toTimeString().substring(0, 8) } }, created () { interval = setInterval(() =>{ let icnow = new Date(); this.year = icnow.getFullYear(); this.month = icnow.getMonth() + 1; this.date = icnow.getDate(); this.day = days[icnow.getDay()]; this.time = icnow.toTimeString().substring(0, 8); }, 1000) }, computed: { // 当前时间 newTime: function () { return this.year + '年' + this.month + '月' + this.date + '日 星期' + this.day + ' ' + this.time; } }, beforeDestroy () { clearInterval(interval); } }

(改为采用计算属性的方式获取时间)HTML模板如下:

{{newTime}}

效果图: 在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3