效果图:
背景描述:
产品提出需求,需要日历来配置每一天的商品价格。刚开始使用的element-ui的el-calendar组件,由于样式、跳转、点击事件等功能都不好控制,所以自己写了一个日历组件。完美符合需求交差。
代码展示:
<div class="dataContent">
<div class="dataMonthContent clearfix">
// 顶部月份切换左箭头
<div>
<span class="prev" @click="clickLeft"></span>
</div>
// 月份
<div class="monthList clearfix">
<ul>
<li>
<span>{{ selectedYear }}年{{ selectedMonth + 1}}月</span>
</li>
</ul>
</div>
// 顶部月份切换右箭头
<div>
<span class="next" @click="clickRight"></span>
</div>
</div>
// 星期
<div class="dataTypeContent clearfix">
<ul>
<li v-for="(item, index) in blockHead" :key="index">
{{ item }}
</li>
</ul>
</div>
// 日期
<div class="dataListContent clearfix">
<ul class="clearfix">
<li
v-for="(item, index) in newDate"
:key="index"
@click="toDetail(item)"
class="dataListContent_list_item"
>
<div class="list_item_date">
{{ item.content }}
</div>
<div class="list_item_msg">
<p>
// 这里可以填写某一天日期需要展示的其他字段
</p>
</div>
</li>
</ul>
</div>
</div>
data:{
return: {
year: new Date().getFullYear(),
month: new Date().getMonth() + 1,
day: new Date().getDate(),
selectedYear: new Date().getFullYear(),
selectedMonth: new Date().getMonth(),
selectedDate: new Date().getDate(),
blockHead: ["日", "一", "二", "三", "四", "五", "六"],
newDate: [],
}
},
mounted() {
this.initDate(this.year, this.month, this.day);
},
methods: {
// 点击切换上个月的日历
clickLeft() {
if (this.selectedMonth === 0) {
this.selectedYear = this.selectedYear - 1;
this.selectedMonth = 11;
this.selectedDate = 1;
} else {
this.selectedMonth = this.selectedMonth - 1;
this.selectedDate = 1;
}
this.initDate(
this.selectedYear,
this.selectedMonth + 1,
this.selectedDate
);
},
// 点击切换下个月的日历
clickRight() {
if (this.selectedMonth === 11) {
this.selectedYear = this.selectedYear + 1;
this.selectedMonth = 0;
this.month = 0;
this.selectedDate = 1;
} else {
this.selectedMonth = this.selectedMonth + 1;
this.month = this.selectedMonth + 1;
this.selectedDate = 1;
}
this.initDate(
this.selectedYear,
this.selectedMonth + 1,
this.selectedDate
);
},
// 获取日历的日期渲染
initDate(year, month, day) {
// 定义每个月的天数,如果是闰年第二月改为29天
// 每个月对应的天数
let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
// 闰年+1天
daysInMonth[1] = 29;
}
// 获得第一天是星期几
let targetDay = new Date(year + "-" + month + "-01").getDay();
let perNum = targetDay;
let info = []; // 存放日历数据列表
// 填充前方空位
if (targetDay > 0) {
for (let i = 0; i < perNum; i++) {
let obj = {
type: "pre",
content: "",
month: month - 1
};
info.push(obj);
}
}
// 填充日期正文数字
for (let i = 0; i < daysInMonth[month - 1]; i++) {
let obj = {
type: "normal",
content: i + 1,
month: month
};
info.push(obj);
}
let nextNum = 0;
if (info.length > 35) {
// 1行7位,超过5行了
nextNum = 42 - info.length;
} else {
nextNum = 35 - info.length;
}
for (let i = 0; i < nextNum; i++) {
let obj = {
type: "next",
content: i + 1,
month: month + 1
};
info.push(obj);
}
this.newDate = info; // 得到新的日历数据
},
// 跳转到详情页面,携带需要的数据
toDetail(val) {
this.$router.push(...)
}
}
样式我在这里就不详细写了,大家各取所需。