以下是模板
<template>
<div>
<!-- 选择月份框(头部) -->
<div
id="showMonth"
@click.stop="showMonth()"
:class="monthShow == true ? 'dateBox true' : 'dateBox'"
>
<label
v-show="arr.length == 0"
style="cursor: pointer; color: rgb(168, 168, 168)"
>开始月份</label
>
<label v-show="arr.length != 0" style="cursor: pointer"
>{{ Firmonth + 1 }}月</label
>
<label style="width: 20px">至</label>
<label
v-show="arr.length == 0"
style="cursor: pointer; color: rgb(168, 168, 168)"
>结束月份</label
>
<label v-show="arr.length != 0" style="cursor: pointer"
>{{ Sedmonth + 1 }}月</label
>
</div>
<!-- 月份选择器 -->
<div
id="monthBox"
v-show="monthShow"
class="monthShow fadein"
>
<!-- 月份区间选择 -->
<div class="months">
<div
class="out"
v-for="(m, index) of months"
:key="m.id"
:class="{
'start-data': index === Firmonth,
'end-data': index === Sedmonth,
'start-month': index === Startmonth,
'other-month': index !== Firmonth && index !== Sedmonth,
}"
:style="
index > Math.min.apply(null, arr) &&
index < Math.max.apply(null, arr)
? outSelect
: ''
"
>
<p
@click="getMonth(index)"
:class="index === Firmonth || index === Sedmonth ? 'active' : ''"
:style="
index > Math.min.apply(null, arr) &&
index < Math.max.apply(null, arr)
? select
: ''
"
>
{{ m }}
</p>
</div>
</div>
</div>
</div>
</template>
以下是主要逻辑代码
<script>
export default {
data() {
return {
count: 0,
monthShow: false,//控制月份选择盒子显示隐藏
year: "",
Firmonth: "",
Sedmonth: "",
Startmonth: "",
month: "",
months: [
"一月",
"二月",
"三月",
"四月",
"五月",
"六月",
"七月",
"八月",
"九月",
"十月",
"十一月",
"十二月",
],
arr: [],
select: {
color: "black",
},
outSelect: {
color: "black",
backgroundColor: "#f2f6fc",
},
};
},
created(){
document.addEventListener("click",e =>{
let box = document.getElementById("monthBox");
if(box.contains(e.target)){
console.log(this);
console.log("内");
}else{
this.monthShow = false;
console.log("外");
}
})
},
methods: {
showMonth() {
this.monthShow = !this.monthShow;
},
getMonth(index) {
let _this = this;
// 通过数组push 检索inde 来判断 是否为第一个选择的月份
if (_this.arr.length < 2) {
_this.arr.push(index);
_this.Firmonth = Math.min.apply(null, _this.arr);
_this.Sedmonth = Math.max.apply(null, _this.arr);
} else {
_this.Firmonth = index;
_this.Sedmonth = index;
_this.arr = [];
_this.arr.push(index);
console.log(_this.arr);
}
},
// 获取当前日期
getInitTime() {
let date = new Date();
this.Startmonth = date.getMonth(); //获取本月
},
},
mounted() {
this.getInitTime();
},
};
</script>