2019-06-26 13:50:21 201浏览
今天千锋扣丁学堂Web前端HTML5培训老师给大家分享一篇关于Vue实现日历小插件的详细介绍,下面我们以前来看一下吧。
<template>
<div class="wrap">
//months是一个包含十二个月名字的数组,用v-for对其进行循环渲染,并且把月份的index传给子组件
<div v-for='(items, index) in months' v-if="index == monthIndex">
<month :monthName='items'
:year='year' //年份传给子组件,年份在mounted里面计算得出
:monthIndex='index' //月份传给子组件
:day='today'//当日日期传给子组件
:key='index' >
</month>
</div>
</div>
</template>
//data部分
data () {
return {
monthIndex: 0,
months:['January', 'February', 'March', 'April',
'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December'],
year:-1,
day:-1,
}
},
//父组件
mounted () {
let myDate = new Date();
this.monthIndex = myDate.getMonth();
this.year = myDate.getFullYear();
this.today = myDate.getDate() - 1;
},
//index值为0-41
<div v-for="(item, index) in days" :key='index'
class="dayIndex" @click='choose(index)'
:class="{choose: day == index}"> //动态绑定样式
if (new Date().getMonth() == this.monthIndex) {
this.chooseIndex = this.day + this.firstDayIndex;
}
new Date(year + '/' + monthIndex + '/' + '01').getDay();
monthLastDay:{
0:31,
1:28,
2:31,
3:30,
4:31,
5:30,
6:31,
7:31,
8:30,
9:31,
10:30,
11:31
},
getMonthLastDay (year, month){
if (month != 1) {
return this.monthLastDay[month];
} else {
//this.leapyear是布尔值 它表示该年是否为闰年
if (this.leapyear) {
return 29;
} else {
return 28;
}
}
},
//index为上个月最后一天的日期 lastDayNum为上个月剩余天数
generateDays (index, lastDayNum) {
let temp = 1;
//这个for循环是push上个月的剩余日期,
for (let i = lastDayNum; i > 0; i--) {
this.days.push([(index - i + 1).toString()]);
}
//index置1,开始push本月天数
index = 1;
for (let i = 0; i < 42 - lastDayNum; i++) {
//闰年二月
if (this.leapyear) {
if (index <= 29) {
this.days.push(index.toString());
}
//非闰年月份
} else if (index <= this.monthLastDay[this.monthIndex]) {
this.days.push(index.toString());
//这个else是push下个月的日期
} else {
this.days.push([temp.toString()]);
temp++;
}
index++;
}
},
<div v-for="(item, index) in days" :key='index'
class="dayIndex" @click='choose(index)'
:class="{choose: chooseIndex == index}">
//item为string 为本月日期
<div v-if="typeof(item) == 'string'">
{{item}}
</div>
//否则为非本月日期 添加class setGrey
<div v-else class="setGrey">
{{item[0]}}
</div>
</div>
【关注微信公众号获取更多学习资料】 【扫码进入HTML5前端开发VIP免费公开课】