封装vant 日期组件实现可以选择年份
<template> <div class="yearMonMain"> <div class="label">{{ label }}</div> <div class="content" @click="onShowDatePicker"> {{ date }} <van-icon name="arrow-up" v-if="showDatePicker == true" /> <van-icon name="arrow-down" v-else /> </div> <van-popup v-model="showDatePicker" position="bottom" ref="pop"> <van-picker v-if="type == 'year'" ref="yearPicker" title="请选择年" show-toolbar :columns="yearList" @confirm="onConfirmYear" @cancel="onCancel" /> <van-datetime-picker v-else v-model="currentDate" :type="type" :title="title" :max-date="maxDate" :min-date="minDate" @confirm="onConfirm" @cancel="onCancel" :formatter="formatter" /> </van-popup> </div> </template> <script> export default { name: "YearMonthSel", data() { let yearList = [] let year = new Date().getFullYear() let month = new Date().getMonth() + 1 let currentDate = new Date() // console.log("YearMonthSel defaultValue===", this.defaultValue) if (this.defaultValue) { if (this.type == "year") { year = this.defaultValue for (let i = 1900; i <= year; i++) { yearList.push({ code: i, text: i }) } } else { year = this.defaultValue[0] month = this.defaultValue[1] currentDate = new Date(year, month) } } return { currentDate, year, month, showDatePicker: false, maxDate: new Date(), minDate: new Date("1900-01-01"), yearList, } }, props: { label: { type: String, default: "选择年月", }, title: { type: String, default: "选择年月", }, type: { type: String, default: "year-month", }, defaultValue: { type: String | Number, default: "", }, }, methods: { formatter(type, val) { if (type === "year") { return `${val}年` } else if (type === "month") { return `${val}月` } return val }, onShowDatePicker() { this.showDatePicker = true setTimeout(() => { if (this.type == "year") { const picker = this.$refs.yearPicker //获取组件实例 if (picker) { picker.setValues([this.year]) //setIndexes()中的参数是一个数组 } } }) }, onConfirm(time) { let date = new Date(time) let year = date.getFullYear() let month = date.getMonth() + 1 if (this.year != year || this.month != month) { this.year = year this.month = month this.$emit("onChange", [year, month]) } this.$emit("onConfirm", [year, month]) this.showDatePicker = false }, onConfirmYear(v) { if (this.year != v.code) { this.year = v.code this.$emit("onChange", v.code) } this.showDatePicker = false this.$emit("onConfirm", v.code) }, onCancel() { this.showDatePicker = false }, }, computed: { date: function() { switch (this.type) { case "year": return this.year + "年" default: return this.year + "年" + this.month + "月" } }, }, } </script> <style lang="less" scoped> .yearMonMain { 100%; display: flex; .label { text-align: center; max- 100px; color: #646566; } } .content { flex-grow: 1; text-align: center; } </style>