v-calendar使用data变量配置attributes的dates属性未高亮问题求解
问题根因
在data()初始化阶段Vue实例还未完成挂载,this没有绑定到当前实例,无法正确读取selectedDay、endDate的值。同时普通的data属性不会响应依赖值的变化,后续你选中日期修改状态后,attributes不会自动更新,因此高亮失效。
修复步骤
1. 移除data中的attributes配置,改为计算属性
计算属性会自动监听依赖的selectedDay、endDate变化,动态生成最新的高亮配置。
2. 修正日期取值逻辑
不要只取日期的day属性,直接使用v-calendar返回的day对象中的完整Date值,避免跨月、跨年时日期计算错误。
3. 简化dayClicked逻辑,不需要手动操作dom类名,高亮样式交给attributes自动处理
完整修改后代码
<template> <div id="calendarContainer"> <DatePicker is-range :attributes='attributes' @dayclick='dayClicked' /> <button class="arrowBtnsLeft" @click="monthBack"><</button> <button class="arrowBtnsRight" @click="monthForward">></button> </div> </template> <script> import DatePicker from 'v-calendar/lib/components/calendar.umd' export default { name: 'calendar', components:{ DatePicker, }, data() { return { selectedDay: null, endDate: null, } }, computed: { attributes() { // 只在起止日期都选中时生成范围高亮 if (!this.selectedDay || !this.endDate) return [] return [ { key: 'selectedRange', highlight:{ start: {fillMode: 'outline'}, end: {fillMode: 'outline'}, color:'red', fillMode:'light' }, dates: { start: this.selectedDay.date, end: this.endDate.date }, } ] } }, methods: { dayClicked(day) { if(this.selectedDay == null){ this.selectedDay = day; }else if(this.selectedDay!== null && this.endDate == null){ // 处理用户选的结束日期早于开始日期的情况,自动交换顺序 if (day.date < this.selectedDay.date) { this.endDate = this.selectedDay this.selectedDay = day } else { this.endDate = day; } }else{ this.selectedDay = day; this.endDate = null; } }, monthForward(){ let newtime = this.context.selectedYMD.split('-') var timestring = '' newtime[1] = parseInt(newtime[1])+1 newtime[1] = newtime[1].toString() for( let i = 0; i < 3; i ++){ if(i < 2){ timestring+=newtime[i]+'-' }else{ timestring+=newtime[i] } } this.value = timestring }, monthBack(){ let newtime = this.context.selectedYMD.split('-') var timestring = '' newtime[1] = parseInt(newtime[1])-1 newtime[1] = newtime[1].toString() for( let i = 0; i < 3; i ++){ if(i < 2){ timestring+=newtime[i]+'-' }else{ timestring+=newtime[i] } } this.value = timestring } } } </script> <style> #calendarContainer{ position: relative; z-index: 1; width: 50%; height: 50%; } .inTrip{ border-top:1px solid gray; border-bottom:1px solid gray; } .start{ border-radius: 20px; border-left:1px solid gray; border-right:none; background-color:#2E9CFF; color:white; } .end{ border-radius: 20px; border-right:1px solid gray; border-left:none; background-color:#2E9CFF; color:white; } .arrowBtnsLeft{ position:absolute; top:.8em; left:12em; background-color:#afd7f78e; color:#2E9CFF; border: none; margin-left: .5em; margin-right: .5em; border-radius:5px; text-align: center; } .arrowBtnsRight{ position:absolute; top:.8em; left:14em; background-color:#afd7f78e; color:#2E9CFF; border: none; margin-left: .5em; margin-right: .5em; border-radius:5px; text-align: center; } </style>
内容的提问来源于stack exchange,提问作者luther wardle
相关产品推荐
相关产品推荐

