1、布局
<template>
<div class="WorkCanlender">
<div class="content not-select" @mouseup="endMove">
<div
class="calendBox day"
v-for="(item, index) in calendarConfig.headerData"
:key="'header' + index"
>
星期{{ item }}
</div>
<div
class="calendBox day"
v-for="(item, index) in calendarConfig.allData"
:key="'day' + index"
:class="item.select ? 'active' : ''"
@mousedown="startMove($event, item)"
@mouseover="setStatus($event, item)"
>
{{ item.month }}
-
{{ item.value }}
</div>
</div>
</div>
</template>
2、数据
data() {
return {
moveFlag: false, // 是否开始计算移动
calendarConfig: {
headerData: ["日", "一", "二", "三", "四", "五", "六"],
allData: [],
startData: null,
startEvent: null
}
};
},
3、方法
methods: {
getCalendarConfig() {
// 全部的数据
const allData = [];
let weekDayX = 1; // 坐标系X
let weekDayY = 1; // 坐标系Y
let index = 1; // 索引
function setData(obj) {
const defaultObj = {
x: weekDayX,
y: weekDayY,
select: false,
index: index
};
allData.push(Object.assign(defaultObj, obj));
weekDayX++;
index++;
if (weekDayX === 8) {
weekDayY += 1;
weekDayX = 1;
}
}
const now = new Date(); //当前日期
const nowMonth = now.getMonth(); //当前月
const nowYear = now.getFullYear(); //当前年
const monthStartDate = new Date(nowYear, nowMonth, 1); //本月的开始时间
const monthEndDate = new Date(nowYear, nowMonth + 1, 0); //本月的结束时间
// 获取前空白格
const beforeMonthDate = new Date(nowYear, nowMonth, 0); //上月的开始时间
const maxBeforeDate = beforeMonthDate.getDate(); // 上个月总天数
const maxDay = monthStartDate.getDay()
if (maxDay > 0) {
for (let i = 0; i < maxDay; i++) {
const beforeObj = {
value: maxBeforeDate - maxDay + i + 1,
month: nowMonth
};
setData(beforeObj);
}
}
// 获取本月格子
const endDate = monthEndDate.getDate(); // 本月一共多少天
for (let i = 0; i < endDate; i++) {
const calendObj = {
value: i + 1,
month: nowMonth + 1
};
setData(calendObj);
}
const maxAfterDate = weekDayX;
// 获取后空白格
for (let i = 0; i < 8 - maxAfterDate; i++) {
const afterObj = {
value: i + 1,
month: nowMonth + 2
};
setData(afterObj);
}
this.calendarConfig.allData = allData;
},
startMove(event, item) {
this.calendarConfig.startEvent = event;
this.calendarConfig.startData = item;
item.select = !item.select;
this.moveFlag = true;
},
setStatus(event, item) {
if (this.moveFlag) {
let startIndex = 0;
let endIndex = 0;
if (this.calendarConfig.startData.index > item.index) {
startIndex = item.index;
endIndex = this.calendarConfig.startData.index;
} else {
endIndex = item.index;
startIndex = this.calendarConfig.startData.index;
}
this.calendarConfig.allData.forEach(i => {
if (i.index >= startIndex && i.index <= endIndex) {
i.select = true;
} else {
i.select = false;
}
});
}
},
endMove(event, item) {
this.moveFlag = false;
}
}
4 样式
<style lang="scss">
.WorkCanlender {
width: 100%;
height: 100%;
.content {
width: 100%;
height: 100%;
display: flex;
flex-wrap: wrap;
.calendBox {
width: 14.28%;
background-color: #fff;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #ddd;
}
.active {
background: aquamarine;
}
}
}
</style>
5 样例