vue实现日期组件
Vue 日期组件的实现方法
使用原生 HTML5 input[type="date"]
<template>
<input type="date" v-model="selectedDate" @change="handleDateChange">
</template>
<script>
export default {
data() {
return {
selectedDate: ''
}
},
methods: {
handleDateChange() {
console.log('Selected date:', this.selectedDate)
}
}
}
</script>
这种方法简单直接,但样式和功能受浏览器限制。
使用第三方库(如 Element UI)
安装 Element UI:
npm install element-ui -S
注册组件后使用:
<template>
<el-date-picker
v-model="value"
type="date"
placeholder="选择日期"
@change="handleChange">
</el-date-picker>
</template>
<script>
export default {
data() {
return {
value: ''
}
},
methods: {
handleChange(val) {
console.log('Selected date:', val)
}
}
}
</script>
自定义日期选择器组件
创建自定义组件 DatePicker.vue:
<template>
<div class="date-picker">
<input
type="text"
v-model="displayDate"
@focus="showCalendar = true"
@blur="handleBlur">
<div class="calendar" v-show="showCalendar">
<div class="calendar-header">
<button @click="prevMonth">←</button>
<span>{{ currentMonth }}</span>
<button @click="nextMonth">→</button>
</div>
<div class="calendar-body">
<!-- 日期渲染逻辑 -->
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
displayDate: '',
showCalendar: false,
currentDate: new Date()
}
},
computed: {
currentMonth() {
return this.currentDate.toLocaleString('default', { month: 'long', year: 'numeric' })
}
},
methods: {
prevMonth() {
this.currentDate = new Date(this.currentDate.setMonth(this.currentDate.getMonth() - 1))
},
nextMonth() {
this.currentDate = new Date(this.currentDate.setMonth(this.currentDate.getMonth() + 1))
},
handleBlur() {
setTimeout(() => {
this.showCalendar = false
}, 200)
}
}
}
</script>
使用 Vue 3 Composition API
<template>
<date-picker v-model="date" />
</template>
<script>
import { ref } from 'vue'
import DatePicker from 'v-calendar/lib/components/date-picker.umd'
export default {
components: {
DatePicker
},
setup() {
const date = ref(new Date())
return { date }
}
}
</script>
关键功能实现要点
日期格式化可使用 moment.js 或 date-fns:
import { format } from 'date-fns'
format(new Date(), 'yyyy-MM-dd')
处理日期范围:
methods: {
isDisabledDate(date) {
return date < new Date() // 禁用过去的日期
}
}
样式优化建议
为自定义组件添加基础样式:
.date-picker {
position: relative;
}
.calendar {
position: absolute;
z-index: 1000;
background: white;
border: 1px solid #ddd;
padding: 10px;
}
.calendar-header {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
}






