You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Vuetify v-calendar:按选中日期显示事件名称

解决方案:让V Calendar事件显示在选中的日期上

好问题!要实现把事件名称显示在selected_days对应的周一、周三、周五上,而不是默认的每周起始位置,你可以通过以下两种常用方法来解决:

方法一:将原始事件转换为每日事件条目(推荐)

核心思路是把你的跨月重复事件,拆分成每个选中日期的独立事件。这样V Calendar就能自动把每个事件渲染到对应的日期上。

步骤1:编写日期转换函数

首先写一个辅助函数,遍历事件的日期范围,筛选出属于selected_days的日期,然后生成对应的事件数组:

// 生成两个日期之间的所有日期
function getDatesInRange(startDate, endDate) {
  const dates = [];
  const currentDate = new Date(startDate);
  while (currentDate <= new Date(endDate)) {
    dates.push(new Date(currentDate));
    currentDate.setDate(currentDate.getDate() + 1);
  }
  return dates;
}

// 你的原始事件
const originalEvent = { 
  name: 'Sample Event', 
  starting_date: '2020-10-01', 
  ending_date: '2020-10-31', 
  selected_days: [1, 3, 5] // 1=周一,3=周三,5=周五
};

// 转换为对应选中日期的事件数组
const convertedEvents = getDatesInRange(originalEvent.starting_date, originalEvent.ending_date)
  .filter(date => {
    // 把JS的getDay()结果(0=周日,6=周六)转换为V Calendar的周几格式(1=周一,7=周日)
    const dayOfWeek = date.getDay() === 0 ? 7 : date.getDay();
    return originalEvent.selected_days.includes(dayOfWeek);
  })
  .map(date => ({
    name: originalEvent.name,
    date: date.toISOString().split('T')[0] // 格式化为YYYY-MM-DD
  }));

步骤2:在V Calendar中使用转换后的事件

直接把convertedEvents绑定到组件的events属性即可:

<v-calendar :events="convertedEvents" />

这种方法的优点是逻辑简单,V Calendar会自动处理事件的显示和样式,适合大多数场景。


方法二:使用自定义事件插槽(无需转换事件数组)

如果你不想提前转换事件数据,可以通过V Calendar的event插槽自定义渲染逻辑,判断当前日期是否属于事件的selected_days,再显示事件名称。

模板代码

<v-calendar :events="[originalEvent]">
  <template #event="{ event, day }">
    <!-- 检查当前日期是否在事件的日期范围内,且属于选中的周几 -->
    <div v-if="isValidEventDay(day.date, event)" class="event-name">
      {{ event.name }}
    </div>
  </template>
</v-calendar>

对应的判断方法

在组件的methods中添加判断逻辑:

methods: {
  isValidEventDay(date, event) {
    // 转换周几格式
    const dayOfWeek = date.getDay() === 0 ? 7 : date.getDay();
    // 检查日期是否在事件的起始和结束日期之间
    const eventStart = new Date(event.starting_date);
    const eventEnd = new Date(event.ending_date);
    const currentDate = new Date(date);
    
    return currentDate >= eventStart && currentDate <= eventEnd && event.selected_days.includes(dayOfWeek);
  }
}

这种方法适合事件数据无法提前转换的场景,比如动态获取的事件,但需要自己处理样式和渲染逻辑。

内容的提问来源于stack exchange,提问作者user12970683

火山引擎 最新活动