<template>
<div class='date-format'>
<div class="date-box">
<div class="item" v-for="(item,index) in weekList" :class="{active:currentIndex === index }" @click="active(index)" :key="index">{{ item.week }}
</div>
</div>
</div>
</template>
<script>
export default {
name: 'DateFormat',
data () {
return {
currentIndex: 6, // 当前选中索引
weekList: []
}
},
created () {
this.init()
},
methods: {
init () {
for (let i = 6; i >= 0; i--) {
const today = new Date()
//设置本月天数
today.setDate(today.getDate() - i)
this.format(today)
}
},
// 设置返回格式
format (today) {
const currentDay = new Date()
//获取时间当前时间与参数时间的时间戳 来判断当前显示格式
const diff = currentDay.getTime() - today.getTime()
const diffDays = Math.floor(diff / (1000 * 3600 * 24))
let week = ''
const day =//日
parseInt(today.getDate()) > 9 ? today.getDate() : '0' + today.getDate()
const month =//月
parseInt(today.getMonth()) + 1 > 9
? today.getMonth() + 1
: '0' + (today.getMonth() + 1)
const year = today.getFullYear()//年
if (diffDays === 0) {
week = '当天'
} else if (diffDays === 1) {
week = '昨天'
} else if (diffDays === 2) {
week = '前天'
} else {
week = '周' + ['日', '一', '二', '三', '四', '五', '六'][today.getDay()]
}
const obj = {
id: this.weekList.length + 1,
week,
year,
month,
day,
date: year + '-' + month + '-' + day
}
this.weekList.push(obj)
},
// 切换选中选中状态
active (index) {
this.currentIndex = index
const obj = this.weekList[index]
this.$emit('activeIndex', obj)
}
}
}
</script>
<style lang="scss" scoped>
.date-box{
display: flex;
justify-content: space-around;
align-items: center;
height: 50px;
padding: 10px;
font-size: 18px;
font-weight: bold;
border-bottom: 1px solid #eee;
.item{
display: flex;
justify-content: center;
align-items: center;
}
.active{
color: #3f7b91;
}
}
</style>
效果图