1. 程式人生 > 其它 >vue lic 展示當前時間元件

vue lic 展示當前時間元件

技術標籤:Vuevuevue.js

效果展示
在這裡插入圖片描述
在vue lic 的components資料夾下,新建元件CurrentTime.vue
直接上元件程式碼:

<template>
  <div>
      {{ nowDate + ' ' + nowTime + ' ' + nowWeek }}
  </div>
</template>

<script>
export default {
  name: 'CurrentTime',
    data() {
        return {
            nowDate:
"", // 當前日期 nowTime: "", // 當前時間 nowWeek: "" // 當前星期 }; }, methods: { currentTime() { setInterval(this.getDate, 500); }, getDate: function() { var _this = this; let yy =
new Date().getFullYear(); let mm = new Date().getMonth() + 1; let dd = new Date().getDate(); let week = new Date().getDay(); let hh = new Date().getHours(); let mf = new Date().getMinutes() < 10 ? "0"
+ new Date().getMinutes() : new Date().getMinutes(); if (week == 1) { this.nowWeek = "星期一"; } else if (week == 2) { this.nowWeek = "星期二"; } else if (week == 3) { this.nowWeek = "星期三"; } else if (week == 4) { this.nowWeek = "星期四"; } else if (week == 5) { this.nowWeek = "星期五"; } else if (week == 6) { this.nowWeek = "星期六"; } else { this.nowWeek = "星期日"; } _this.nowTime = hh + ":" + mf; _this.nowDate = yy + "/" + mm + "/" + dd; } }, mounted() { this.currentTime(); }, // 銷燬定時器 beforeDestroy: function() { if (this.getDate) { console.log("銷燬定時器") clearInterval(this.getDate); // 在Vue例項銷燬前,清除時間定時器 } } };
</script>

新增元件
App.vue中,新增以下程式碼

<script>
import CurrentTime from './components/currentTime.vue'

export default {
    components: {
    CurrentTime
  },
}
</script>

且在app中新增 <current-time></current-time>