nathanreyes / v-calendar

An elegant calendar and datepicker plugin for Vue.
https://vcalendar.io
MIT License
4.32k stars 841 forks source link

[Question] How to access the V-Calendar instance to get the current month displayed #1429

Open lessainspasorchies opened 6 months ago

lessainspasorchies commented 6 months ago

Hi,

There are a lot of grey areas in the docs, but a lot of digging and code reading helped me get where I wanted to be except 1 thing:

Edit: I understand I can trigger a new fetch request with the @update:pages event, but I still haven't found where to extract the current month from the Page object/array to allow passing that as a parameter or query in my fetch request

lessainspasorchies commented 6 months ago

Solution:

Don't know if this is the best way, but I have created a ref on the VCal instance, load the initial view containing 'today' (sync) then refetching my data when the vcalendar ref is available (async).

<template>
   <VCalendar
      v-if="!pending"
      ref="vcalendar"
      :initial-page="{ month: today.getMonth() + 1, year: today.getFullYear() }"
      :attributes="attributes"
      @update:pages="() => refresh()"
   />
</template>

<script setup lang="ts>
   import { Calendar as VCalendar } from 'v-calendar';
   import type { AttributeConfig } from 'v-calendar/dist/types/src/utils/attribute';
   import type { Page } from 'v-calendar/dist/types/src/utils/page';

   const today = new Date();
   const vcalendar = ref<typeof VCalendar>();

   const currentPage = computed(() => {
      if (vcalendar.value && vcalendar.value.pages[0]) {
      return vcalendar.value.pages[0] as Page;
      }
   });

   const { data: attributes, error, pending, refresh } = await useFetch<AttributeConfig[]>(
   () =>
      `/api/vcevents?month=${
      (currentPage.value?.month as number) ?? today.getMonth() + 1
      }&year=${(currentPage.value?.year as number) ?? today.getFullYear()}`
   );
</script>