vue实现日历多选
Vue 实现日历多选功能
安装依赖
使用 v-calendar 库可以快速实现日历多选功能。通过 npm 或 yarn 安装:
npm install v-calendar
基本配置
在 Vue 项目中引入 v-calendar 并注册组件:
import VCalendar from 'v-calendar';
import 'v-calendar/dist/style.css';
Vue.use(VCalendar);
实现多选功能
在模板中使用 <v-date-picker> 组件,并通过 mode="multiple" 开启多选模式:
<template>
<v-date-picker
v-model="selectedDates"
mode="multiple"
:min-date="new Date()"
:attributes="attrs"
/>
</template>
<script>
export default {
data() {
return {
selectedDates: [],
attrs: [
{
highlight: {
color: 'blue',
fillMode: 'light',
},
},
],
};
},
};
</script>
自定义样式与交互
通过 :attributes 绑定高亮样式,标记已选日期。selectedDates 数组会动态更新用户选择的日期。
处理日期范围
如果需要选择日期范围而非离散日期,将 mode 改为 'range':
<v-date-picker v-model="range" mode="range" />
禁用特定日期
通过 :disabled-dates 属性禁用不可选的日期(如周末):
data() {
return {
disabledDates: [
{ weekdays: [1, 7] } // 禁用周末
]
};
}
事件监听
监听 input 事件以处理日期选择变化:
<v-date-picker
@input="handleDateChange"
v-model="selectedDates"
mode="multiple"
/>
移动端适配
v-calendar 默认支持响应式设计,若需进一步优化移动端体验,可添加 CSS 媒体查询:
@media (max-width: 640px) {
.vc-container {
width: 100%;
}
}
完整示例
以下是一个完整的多选日历组件示例:
<template>
<div>
<v-date-picker
v-model="selectedDates"
mode="multiple"
:min-date="new Date()"
:disabled-dates="disabledDates"
:attributes="attrs"
@input="logDates"
/>
<p>已选日期: {{ selectedDates.join(', ') }}</p>
</div>
</template>
<script>
export default {
data() {
return {
selectedDates: [],
attrs: [
{
highlight: {
color: 'green',
fillMode: 'solid',
},
},
],
disabledDates: [
{ weekdays: [1, 7] },
],
};
},
methods: {
logDates() {
console.log('Selected Dates:', this.selectedDates);
},
},
};
</script>






