VueDatePicker移动端添加自定义关闭按钮(auto-apply致action-row消失)
解决方案:开启auto-apply后添加自定义关闭按钮
针对你使用@vuepic/vue-datepicker ^7.4.1版本,开启auto-apply后无法通过action-row添加关闭按钮的问题,提供两种可行方案:
方案一:使用close-button插槽(推荐,适配移动端右上角位置)
组件内置close-button插槽,无论是否开启auto-apply都能自定义关闭按钮,默认位置在弹窗右上角,匹配移动端常见的关闭按钮布局。
修改后代码:
<template> <VueDatePicker ref="datePicker" v-model="dates" range :enable-time-picker="false" :multi-calendars="{ solo: true }" placeholder="Select date range" :max-date="new Date()" :auto-apply="true" :format="`dd MMM yyyy`" :preset-dates="presetDates" :end-year="new Date().getFullYear()" @internal-model-change="onchange" > <template #preset-date-range-button="{ label, value, presetDate }"> <span role="button" :tabindex="0" @click="presetDate(value)" @keyup.enter.prevent="presetDate(value)" @keyup.space.prevent="presetDate(value)" > {{ label }} </span> </template> <!-- 自定义关闭按钮插槽 --> <template #close-button> <button class="custom-close-btn" @click="closeDatePicker">关闭</button> </template> </VueDatePicker> </template> <script> export default { data() { return { dates: null, presetDates: [] // 你的预设日期数据 }; }, methods: { onchange() { // 你的业务处理逻辑 }, closeDatePicker() { // 调用组件实例的close方法关闭弹窗 this.$refs.datePicker.close(); } } }; </script> <style scoped> .custom-close-btn { /* 自定义按钮样式,适配移动端 */ padding: 4px 12px; border: none; background: #f5f5f5; border-radius: 4px; cursor: pointer; } </style>
方案二:强制显示action-row并添加按钮(适合底部位置)
如果你的红框位置在弹窗底部,可通过CSS强制显示被auto-apply隐藏的action-row,再通过插槽添加关闭按钮:
修改后代码:
<template> <VueDatePicker ref="datePicker" v-model="dates" range :enable-time-picker="false" :multi-calendars="{ solo: true }" placeholder="Select date range" :max-date="new Date()" :auto-apply="true" :format="`dd MMM yyyy`" :preset-dates="presetDates" :end-year="new Date().getFullYear()" @internal-model-change="onchange" > <template #preset-date-range-button="{ label, value, presetDate }"> <span role="button" :tabindex="0" @click="presetDate(value)" @keyup.enter.prevent="presetDate(value)" @keyup.space.prevent="presetDate(value)" > {{ label }} </span> </template> <!-- 自定义action-row内容 --> <template #action-row> <button class="custom-close-btn" @click="closeDatePicker">关闭</button> </template> </VueDatePicker> </template> <script> export default { data() { return { dates: null, presetDates: [] // 你的预设日期数据 }; }, methods: { onchange() { // 你的业务处理逻辑 }, closeDatePicker() { this.$refs.datePicker.close(); } } }; </script> <style> /* 强制显示被auto-apply隐藏的action-row */ .vdp-action-row { display: flex !important; justify-content: flex-end; padding: 8px 16px; } .custom-close-btn { padding: 6px 16px; border: none; background: #e74c3c; color: white; border-radius: 4px; cursor: pointer; } </style>
说明:
- 方案一利用组件原生插槽,无需额外CSS,符合组件设计规范,优先推荐。
- 方案二通过CSS强制显示隐藏区域,适合需要在底部放置关闭按钮的场景。
内容的提问来源于stack exchange,提问作者Ruhith Udakara
相关产品推荐
相关产品推荐

