问题:pickerOptions: {disabledDate: (time) => {}}使用data中的变量报错
pickerOptions: {
disabledDate(time) {
console.log(this.publishTime);
const now = Date.now();
const threeMonthsAgo = now - 3 * 30 * 24 * 60 * 60 * 1000; // 当前时间前三个月
const threeMonthsLater = now + 3 * 30 * 24 * 60 * 60 * 1000; // 当前时间后三个月
return (
time.getTime() < threeMonthsAgo ||
time.getTime() > threeMonthsLater
);
},
},
原因:箭头函数引起的this指向问题
解决:改为箭头函数方式
<template>
<div class="app-container">
<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
<el-form-item label="时间选择">
<el-date-picker
v-model="dateRange"
style="width: 240px"
value-format="yyyy-MM-dd HH:mm:ss"
type="datetimerange"
range-separator="-"
start-placeholder="开始时间"
end-placeholder="结束时间"
:clearable="false"
:picker-options="pickerOptions"
></el-date-picker>
</el-form-item>
</el-form>
</div>
</template>
<script>
import { listConfig } from "@/api/system/config";
export default {
name: "Settings",
data() {
return {
queryParams: {},
publishTime: null,
publishTimePeriod: null,
dateRange: ["2023-09-01 00:00:00", "2023-09-02 00:00:00"],
pickerOptions: {
disabledDate: (time) => {
const now = Date.now();
const threeMonthsAgo = new Date(this.publishTime).getTime(); // 当前时间前三个月
const threeMonthsNow = now + 0 * 30 * 24 * 60 * 60 * 1000; // 当前时间
const threeMonthsLater = threeMonthsAgo + this.publishTimePeriod * 30 * 24 * 60 * 60 * 1000; // 当前时间后三个月
let threeMonthsLater2;
if (threeMonthsLater > threeMonthsNow) {
threeMonthsLater2 = threeMonthsLater
} else {
threeMonthsLater2 = threeMonthsNow
}
return (
time.getTime() < threeMonthsAgo ||
time.getTime() > threeMonthsLater2
);
},
},
};
},
created() {
this.getPublishTime();
},
methods: {
async getPublishTime() {
const configKey = {
configKey: "sys_publish_time",
pageNum: 1,
pageSize: 10,
};
const response = await listConfig(configKey);
if (response.rows.length > 0) {
const tempPublishTime = response.rows[0].configValue; // 2023-09-01 00:00:00#6
this.publishTime = tempPublishTime.split("#")[0]; // 2023-09-01 00:00:00
this.publishTimePeriod = parseInt(tempPublishTime.split("#")[1]); // 6
} else {
this.publishTime = null;
this.publishTimePeriod = null;
}
},
},
};
</script>