需求背景
在Vant 的日歷組件中想要禁用某些指定的日期,但是Vant 並沒有提供類型disabledDate
這樣的的選項給我們配置。
通過閱讀Vant 的 calendar組件源碼,可以發現當這個日期的 type
屬性值為 disabled
時,就會禁用當前日期。
我們可以通過formatter
這個屬性來重新定義每一個日期的數據。從而改變 type
的屬性值。
實現方法
示例:所有的周日都不可選
<van-calendar
title="日歷"
:min-date="minDate"
:max-date="maxDate"
:poppable="false"
:formatter="formatter"
:show-confirm="false"
:style="{ height: '380px' }"
/>
methods:{
formatter(day){
/*
這里的參數包含以下屬性
bottomInfo: undefined
date: Sat May 22 2021 00:00:00 GMT+0800 (中國標准時間) {}
text: 22
type: "
我們只需要修改type值為 disabled 即可
*/
// 周日全天不可選
let week = day.date.getDay()
if(week == 0){
day.type = 'disabled'
}
return day
}
}
原理分析
如果 type === 'disabled'
則當前日期禁用
// 生成單個日期
genDay: function genDay(item, index) {
// ...
var disabled = type === 'disabled';
var onClick = function onClick() {
if (!disabled) {
_this2.$emit('click', item);
}
};
// ...
}
我們可以發現每個日期是通過 days
遍歷生成的。
genDays: function genDays() {
var h = this.$createElement;
var days = this.shouldRender ? this.days : this.placeholders;
return h("div", {
"ref": "days",
"attrs": {
"role": "grid"
},
"class": (0, _utils2.bem)('days')
}, [this.genMark(), days.map(this.genDay)]);
},
days
這個數據是一個計算屬性,如果選項中有formatter
屬性,就會調用,所以我們可以在 formatter
中做我們想要的。
days: function days() {
var days = [];
var year = this.date.getFullYear();
var month = this.date.getMonth();
for (var day = 1; day <= this.totalDay; day++) {
var date = new Date(year, month, day);
var type = this.getDayType(date);
var config = {
date: date,
type: type,
text: day,
bottomInfo: this.getBottomInfo(type)
};
if (this.formatter) {
config = this.formatter(config);
}
days.push(config);
}
return days;
}