完整代码:
<template>
<div :style="{ width: '300px', border: '1px solid #d9d9d9', borderRadius: '4px' }">
<!-- 日历汉化 -->
<a-config-provider :locale="locale">
<a-calendar :header-render="headerRender" @select="onSelect" :fullscreen="false">
<div slot="dateCellRender" slot-scope="value">
<template v-for="(item,index) in restDay">
<span :key="index" class="restCls" v-if="moment(value).format('YYYY-MM-DD') == item">
</span>
</template>
</div>
</a-calendar>
</a-config-provider>
</div>
</template>
<script>
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN';
import moment from 'moment';
export default {
data() {
return {
moment,//moment必须在data里定义后才能在template里直接使用
locale: zhCN,
selectedValue: '',
restDay: ['2023-02-03','2023-02-04','2023-02-05'],
};
},
methods: {
headerRender({ value, type, onChange, onTypeChange }) {
const start = 0;
const end = 12;
const monthOptions = [];
const current = value.clone();
const localeData = value.localeData();
const months = [];
for (let i = 0; i < 12; i++) {
current.month(i);
months.push(localeData.monthsShort(current));
}
for (let index = start; index < end; index++) {
monthOptions.push(
<a-select-option class="month-item" key={`${index}`}>
{months[index]}
</a-select-option>,
);
}
const month = value.month();
const year = value.year();
const options = [];
for (let i = year - 10; i < year + 10; i += 1) {
options.push(
<a-select-option key={i} value={i} class="year-item">
{i}
</a-select-option>,
);
}
return (
<div style={{ padding: '10px' }}>
<a-row type="flex" justify="space-between">
<a-col>
<a-select
size="small"
dropdownMatchSelectWidth={false}
class="my-year-select"
onChange={newYear => {
const now = value.clone().year(newYear);
onChange(now);
}}
value={String(year)}
>
{options}
</a-select>
</a-col>
<a-col>
<a-select
size="small"
dropdownMatchSelectWidth={false}
value={String(month)}
onChange={selectedMonth => {
const newValue = value.clone();
newValue.month(parseInt(selectedMonth, 10));
onChange(newValue);
}}
>
{monthOptions}
</a-select>
</a-col>
</a-row>
</div>
);
},
onSelect(value) {
this.value = value;
this.selectedValue = value;
console.log("select:"+moment(this.selectedValue).format('YYYY-MM-DD'))
},
},
};
</script>
<style scoped>
.restCls {
position: relative;
top: -10px;
width: 28px;
height: 28px;
border-radius: 50%;
display: inline-block;
left: 0px;
border: 2px solid #1890ff;
}
/deep/ .ant-fullcalendar-value{
width: 28px;
height: 28px;
border-radius: 50%;
}
</style>
最终效果:
难点:
自定义头部:参考官网即可,我的日历头部右边只需要显示月,不需要年,把年的部分去掉即可。
在template里直接用moment,先import然后还需要在data里再定义一下moment。
日历默认是英文的,需要汉化,参考官网,如果是做项目的话,直接在App.vue文件里设置,整个项目的antd组件就都被汉化了。
参考博客:
https://blog.csdn.net/yehaocheng520/article/details/123730865