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>
dayjs利用插件
查看效果
- npm安装
npm install dayjs --save
- 添加到main.js
import dayjs from ‘dayjs’
Vue.use(dayjs)
- 结合定时器,在app中测试查看效果
<template>
<div id="app">
<span>{{today}}</span>
</div>
</template>
<script>
export default {
data () {
return {
today: ''
}
},
mounted () {
setInterval(() => {
var dayjs = require('dayjs')
this.today = dayjs().format('YYYY-MM-DD HH:mm:ss')
}, 100)
}
}
</script>