vue datepicker 实现
Vue Datepicker 实现方法
使用第三方库(推荐)
安装 vue-datepicker 或 v-calendar 等流行库,例如:
npm install vuejs-datepicker
在组件中引入并使用:

<template>
<datepicker v-model="selectedDate"></datepicker>
</template>
<script>
import Datepicker from 'vuejs-datepicker';
export default {
components: { Datepicker },
data() {
return {
selectedDate: new Date()
}
}
}
</script>
自定义实现基础 Datepicker
创建可重用的 Datepicker 组件:
<template>
<div class="datepicker">
<input
type="text"
v-model="displayDate"
@focus="showPicker = true"
@blur="handleBlur"
>
<div class="calendar" v-if="showPicker">
<!-- 日历头部 -->
<div class="header">
<button @click="prevMonth">←</button>
<span>{{ currentMonth }} {{ currentYear }}</span>
<button @click="nextMonth">→</button>
</div>
<!-- 日历内容 -->
<div class="days">
<div v-for="day in days" :key="day" class="day">
{{ day }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedDate: null,
displayDate: '',
showPicker: false,
currentDate: new Date(),
days: ['日', '一', '二', '三', '四', '五', '六']
}
},
computed: {
currentMonth() {
return this.currentDate.getMonth() + 1
},
currentYear() {
return this.currentDate.getFullYear()
}
},
methods: {
prevMonth() {
this.currentDate = new Date(
this.currentDate.getFullYear(),
this.currentDate.getMonth() - 1,
1
)
},
nextMonth() {
this.currentDate = new Date(
this.currentDate.getFullYear(),
this.currentDate.getMonth() + 1,
1
)
},
handleBlur() {
setTimeout(() => {
this.showPicker = false
}, 200)
}
}
}
</script>
<style>
.datepicker {
position: relative;
}
.calendar {
position: absolute;
border: 1px solid #ccc;
padding: 10px;
background: white;
z-index: 100;
}
</style>
高级功能扩展
为自定义 Datepicker 添加更多功能:

// 在 methods 中添加日期选择方法
selectDate(date) {
this.selectedDate = date
this.displayDate = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`
this.showPicker = false
}
// 计算当月天数
getDaysInMonth() {
return new Date(
this.currentDate.getFullYear(),
this.currentDate.getMonth() + 1,
0
).getDate()
}
// 生成日期单元格
generateDates() {
const daysInMonth = this.getDaysInMonth()
const dates = []
for (let i = 1; i <= daysInMonth; i++) {
dates.push(new Date(
this.currentDate.getFullYear(),
this.currentDate.getMonth(),
i
))
}
return dates
}
国际化支持
添加多语言支持:
data() {
return {
locales: {
en: {
days: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
},
zh: {
days: ['日', '一', '二', '三', '四', '五', '六'],
months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
}
},
currentLocale: 'zh'
}
}
日期范围限制
添加 minDate 和 maxDate 限制:
props: {
minDate: {
type: Date,
default: null
},
maxDate: {
type: Date,
default: null
}
},
methods: {
isDateDisabled(date) {
if (this.minDate && date < this.minDate) return true
if (this.maxDate && date > this.maxDate) return true
return false
}
}






