今天放假,自己实现了一个简易版日历,熟悉了下日期对象的基本使用,记录下遇到的难点和报错
暂时坚持样式结构交互都自己实现难点获取当前月份总天数
getdate(){let nexMonth=new Dade().getMonth+1
let d=new Date(new Date,().getFullyear,nexMonth,0);
return d.getDate()
},
2.获取当前月份一号是星期几
报错点在monuted中调用computed的方法时不可以加括号和参数//获取当月1号是星期几
getday(){
let nexMonth=new Date().Month;
let d=new Date(new Date().getFullyear,nexMonth,1);
return d.getDay()
},
//遍历出当月的天数,增加到dates数组中
for (let i=1;i<=this.getdate;i++){
this.dates.push(i)
}
//遍历出当前的1号是星期几,使1号出现在对应的星期几上
for (let i=0; i<this.getday;i++){
this.dates.unshift(this.vacancy)
}
2.要查看上一个月或下一个月时更新模版时不能在monuted实现,在updated能实现,我在watch里实现
watch:{
months(){
//遍历出选择月份的天数,增加到dates数组中
this.dates=[]
for (let i=1;i<=this.getdate;i++){
this.dates.push(i)
}
//遍历出选择月份的1号是星期几,使1号出现在对应的星期几上
for (let i=0; i<this.getday;i++){
this.dates.unshift(this.vacancy)
}
}
}
一.模板结构
<template>
<div class="calendar">
<ul class="calendar-ym">
<li @click="lt"><</li>
<li v-text="`${years}年${months}月`"></li>
<li @click="gt">></li>
</ul>
<ul class="calendar-day">
<li v-for="(itme,index) in days "
:key=itme
:class="{dateclass: new Date().getDay() === index}"
> {{itme}}</li>
</ul>
<ul class="calendar-date">
<li v-for="i in dates"
:key="i"
:class="{dateclass: new Date().getDate()===i }"
>
{{i}}
</li>
</ul>
</div>
</template>
二.数据与操作
<script>
export default {
name: 'Calendar',
data(){
return{
days:["日","一","二","三","四","五","六"],
dates:[],
years:new Date().getFullYear(),
months:new Date().getMonth()+1,
vacancy:null,
}
},
methods:{
//获取上一个月
lt(){
this.months--
if(this.months === 0){
this.months=12
this.years--
}
},
//获取下一个月
gt(){
this.months++
if(this.months === 12){
this.months=1
this.years++
}
},
},
computed:{
//获取当月有多少天
getdate(){
let nexMonth=this.months;
let d=new Date(this.years,nexMonth,0);
return d.getDate()
},
//获取当月1号是星期几
getday(){
let nexMonth=this.months-1;
let d=new Date(this.years,nexMonth,1);
return d.getDay()
},
},
mounted() {
//遍历出当月的天数,增加到dates数组中
for (let i=1;i<=this.getdate;i++){
this.dates.push(i)
}
//遍历出当前的1号是星期几,使1号出现在对应的星期几上
for (let i=0; i<this.getday;i++){
this.dates.unshift(this.vacancy)
}
},
watch:{
months(){
//遍历出选择月份的天数,增加到dates数组中
this.dates=[]
for (let i=1;i<=this.getdate;i++){
this.dates.push(i)
}
//遍历出选择月份的1号是星期几,使1号出现在对应的星期几上
for (let i=0; i<this.getday;i++){
this.dates.unshift(this.vacancy)
}
}
}
}