Vue3 DatePicker:使用highlight时如何指定默认显示的年月?
解决@vuepic/vue3datepicker数组v-model下默认定位指定年月的问题
当v-model设为数组以支持highlight属性时,你可以直接使用组件的view-date prop来控制日历默认显示的年月,无需依赖v-model的取值。
具体实现步骤:
- 定义响应式变量存储目标视图日期,在
onMounted中根据API返回的年月生成对应的Date对象 - 将
view-date绑定到该变量,独立控制日历视图定位 - 保持
v-model为数组类型,不影响高亮功能
代码示例(Vue3 Script Setup):
<template> <DatePicker v-model="selectedDates" :highlight="highlightDates" :view-date="targetViewDate" // 其他所需配置,比如range等 /> </template> <script setup> import { ref, onMounted } from 'vue'; import DatePicker from '@vuepic/vue3-datepicker'; import '@vuepic/vue3-datepicker/dist/main.css'; const selectedDates = ref([]); const highlightDates = ref([]); const targetViewDate = ref(null); onMounted(async () => { // 模拟API获取指定年月,示例返回格式为"2024-06" const apiReturnedYearMonth = await fetch('/api/get-target-month'); // 转换为Date对象(注意JS中月份从0开始,需减1) const [year, month] = apiReturnedYearMonth.split('-'); targetViewDate.value = new Date(Number(year), Number(month) - 1, 1); // 同时获取需高亮的日期数据 highlightDates.value = await fetch('/api/get-highlight-dates'); }); </script>
关键说明:
view-date是@vuepic/vue3datepicker专门用于控制日历视图显示日期的prop,与v-model的类型(单个日期/数组)完全独立- 生成
Date对象时,日期部分设为1即可,视图仅会聚焦对应的年月,不会影响实际选中或高亮的日期
内容的提问来源于stack exchange,提问作者Billal BEGUERADJ
相关产品推荐
相关产品推荐

