You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vuetify v-calendar周视图(view-mode="week")中处理事件点击?

Vuetify v-calendar周视图点击事件触发方案

问题核心

Vuetify的v-calendar组件在不同视图模式下对应不同的事件插槽:event插槽仅在**月视图(view-mode="month")中生效,而周视图(view-mode="week")**需要使用day-event插槽来自定义事件渲染及绑定点击逻辑。

解决方案

将原代码中的#event插槽替换为#day-event,同时可以直接利用组件内置的@click:event事件回调(无需在插槽内重复绑定点击事件,避免冗余)。以下是修改后的完整代码:

<template>
  <v-container>
    <v-calendar
      ref="calendar"
      class="calendar"
      v-model="value"
      :events="events"
      view-mode="week"
      :weekdays="weekday"
      @click:event="handleEventClick"
    >
      <!-- 周视图使用day-event插槽 -->
      <template #day-event="{ event }">
        <v-card
          class="d-inline-block ma-2"
          :color="event.color"
        >
          <v-card-title>{{ event.title }}</v-card-title>
        </v-card>
      </template>
    </v-calendar>

    <v-menu
      v-model="menuVisible"
      :activator="selectedElement"
      offset-x
    >
      <v-card>
        <v-card-title>{{ selectedEvent?.title }}</v-card-title>
        <v-card-actions>
          <v-btn text @click="menuVisible = false">Close</v-btn>
        </v-card-actions>
      </v-card>
    </v-menu>
  </v-container>
</template>

<script setup>
import { ref } from 'vue'

const value = ref([new Date()])
const events = ref([
  { id: 1, title: 'Event 1', start: new Date(), end: new Date(), color: 'light-blue' },
  { id: 2, title: 'Event 2', start: new Date(), end: new Date(), color: 'red' },
])

const menuVisible = ref(false)
const selectedElement = ref(null)
const selectedEvent = ref(null)

function handleEventClick({ event, nativeEvent }) {
  console.log('Event clicked:', event.title)
  selectedEvent.value = event
  selectedElement.value = nativeEvent.target
  menuVisible.value = true
}
</script>

<style scoped>
.calendar {
  background-color: #fdfdfd;
}
</style>

关键说明

  1. 插槽替换:周视图下必须使用day-event插槽来渲染单日事件,原event插槽仅适用于月视图。
  2. 事件回调优化:直接使用v-calendar的@click:event事件即可获取事件对象和原生事件,无需在插槽内的v-card上重复绑定点击事件,减少代码冗余。
  3. 样式适配:将卡片颜色绑定到事件的color字段,保持事件样式与数据的一致性。

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 04:25:09