A month-view calendar is often treated as a case for a plugin or an embedded Google Calendar, but building one directly in Vue is not much work — especially when the component model is carrying the logic. The target here is a single page application whose dates come from Day.js: a full month grid, dates from the adjacent months filling out the rows, a marker for today, a label for the selected month, previous/next navigation, and a one-click return to the current month.

Splitting the grid into components

The main component lives in CalendarMonth.vue, and its markup has three layers:

  • The calendar header — the selected month plus the controls that paginate between months.
  • The calendar grid header — a table header holding the weekday names, starting with Monday.
  • The calendar grid — one square per day.

Building on that skeleton, the header splits into CalendarDateIndicator and CalendarDateSelector, and the grid into CalendarWeekdays and CalendarMonthDayItem.

Header components

Showing the selected month

CalendarDateIndicator takes a selectedDate prop, which is a Day.js object on which the component's formatting is applied for display.

<!-- CalendarDateIndicator.vue -->
<template>
  <div class="calendar-date-indicator">{{ selectedMonth }}</div>
</template>

<script>
export default {
  props: {
    selectedDate: {
      type: Object,
      required: true
    }
  },

  computed: {
    selectedMonth() {
      return this.selectedDate.format("MMMM YYYY");
    }
  }
};
</script>

Paginating between months

CalendarDateSelector holds three elements for the previous, current and next month, each with an event listener that fires the matching method on click.

<!-- CalendarDateSelector.vue -->
<template>
  <div class="calendar-date-selector">
    <span @click="selectPrevious">﹤</span>
    <span @click="selectCurrent">Today</span>
    <span @click="selectNext">﹥</span>
  </div>
</template>

The script section declares two props: currentDate, which lets the "Today" button jump back to the current month, and selectedDate, the month currently in view. Methods then derive the new selected date from the existing one via Day.js's subtract and add, and each method $emits the newly selected month up to the parent. Keeping the selected date in one place — CalendarMonth.vue — means it can then be passed down to every child component, header and grid alike.

// CalendarDateSelector.vue
<script>
import dayjs from "dayjs";

export default {
  name: "CalendarDateSelector",

  props: {
    currentDate: {
      type: String,
      required: true
    },

    selectedDate: {
      type: Object,
      required: true
    }
  },

  methods: {
    selectPrevious() {
      let newSelectedDate = dayjs(this.selectedDate).subtract(1, "month");
      this.$emit("dateSelected", newSelectedDate);
    },

    selectCurrent() {
      let newSelectedDate = dayjs(this.currentDate);
      this.$emit("dateSelected", newSelectedDate);
    },

    selectNext() {
      let newSelectedDate = dayjs(this.selectedDate).add(1, "month");
      this.$emit("dateSelected", newSelectedDate);
    }
  }
};
</script>

Wiring the header into the parent

Back in CalendarMonth.vue, both components need to be imported and registered. The parent also supplies two values for props: today, which formats today's date and feeds the "Today" button, and selectedDate, defaulting to today's date. One more method receives the pagination component's emitted event and updates selectedDate.

// CalendarMonth.vue
<script>
import dayjs from "dayjs";
import CalendarDateIndicator from "./CalendarDateIndicator";
import CalendarDateSelector from "./CalendarDateSelector";

export default {
  components: {
    CalendarDateIndicator,
    CalendarDateSelector
  },

  data() {
    return {
      selectedDate: dayjs(),
      today: dayjs().format("YYYY-MM-DD")
    };
  },

  methods: {
    selectDate(newSelectedDate) {
      this.selectedDate = newSelectedDate;
    }
  }
};
</script>

With that, the header renders:

<!-- CalendarMonth.vue -->
<template>
  <div class="calendar-month">
    <div class="calendar-month-header">
      <CalendarDateIndicator
        :selected-date="selectedDate"
        class="calendar-month-header-selected-month"
      />
      <CalendarDateSelector
        :current-date="today"
        :selected-date="selectedDate"
        @dateSelected="selectDate"
      />
    </div>
  </div>
</template>

Grid components

CalendarWeekdays renders the labels of the weekdays: a list iterates the labels with v-for and renders one for each. The labels are defined in the script section and exposed through a computed property, which caches the result so it is not recalculated later.

// CalendarWeekdays.vue
<template>
  <ol class="day-of-week">
    <li
      v-for="weekday in weekdays"
      :key="weekday"
    >
      {{ weekday }}
    </li>
  </ol>
</template>


<script>
const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

export default {
  name: 'CalendarWeekdays',

  computed: {
    weekdays() {
      return WEEKDAYS
    }
  }
}
</script>

CalendarMonthDayItem is a list item with a day object prop and an isToday boolean that lets the item be styled as the current date. A single computed property formats the received day object into the desired date format — D, the numeric day of the month.

// CalendarMonthDayItem.vue
<template>
  <li
    class="calendar-day"
    :class="{
      'calendar-day--not-current': !isCurrentMonth,
      'calendar-day--today': isToday
    }"
  >
    <span>{{ label }}</span>
  </li>
</template>


<script>
import dayjs from "dayjs";

export default {
  name: "CalendarMonthDayItem",

  props: {
    day: {
      type: Object,
      required: true
    },

    isCurrentMonth: {
      type: Boolean,
      default: false
    },

    isToday: {
      type: Boolean,
      default: false
    }
  },

  computed: {
    label() {
      return dayjs(this.day.date).format("D");
    }
  }
};
</script>

After importing and registering both components, CalendarMonth needs a computed property returning an array of day objects, each carrying a date and an isCurrentMonth value.

// CalendarMonth.vue
<script>
import dayjs from "dayjs";
import CalendarMonthDayItem from "./CalendarMonthDayItem";
import CalendarWeekdays from "./CalendarWeekdays";


export default {
  name: "CalendarMonth",

  components: {
    // ...
    CalendarMonthDayItem,
    CalendarWeekdays
  },

  computed: {
    days() {
      return [
        { date: "2020-06-29", isCurrentMonth: false },
        { date: "2020-06-30", isCurrentMonth: false },
        { date: "2020-07-01", isCurrentMonth: true },
        { date: "2020-07-02", isCurrentMonth: true },
        // ...
        { date: "2020-07-31", isCurrentMonth: true },
        { date: "2020-08-01", isCurrentMonth: false },
        { date: "2020-08-02", isCurrentMonth: false }
      ];
    }
  }
};
</script>

The template then renders them, again with v-for over the required number of day elements.

<!-- CalendarMonth.vue -->
<template>
  <div class="calendar-month">
    <div class="calendar-month-header">
      // ...
    </div>

    <CalendarWeekdays/>

    <ol class="days-grid">
      <CalendarMonthDayItem
        v-for="day in days"
        :key="day.date"
        :day="day"
        :is-today="day.date === today"
      />
    </ol>
  </div>
</template>

Computing the dates of the current month

At this point the template is static: the month is hardcoded as July and so are the day numbers. Day.js provides the real calendar data for placing dates in the right weekday columns, from the start date of a month to the formatting options. The work is to get the current month, compute where its days land among the weekdays, compute the filler days from the adjacent months, and combine everything into one array.

Two Day.js plugins help. WeekDay sets the first day of the week — Sunday, Monday or, in some cases, Friday; here it is Monday. WeekOfYear returns the numeric week of the year, counting from the week that starts January 1 as week one among the year's 52.

// CalendarMonth.vue
<script>
import dayjs from "dayjs";
import weekday from "dayjs/plugin/weekday";
import weekOfYear from "dayjs/plugin/weekOfYear";
// ...


dayjs.extend(weekday);
dayjs.extend(weekOfYear);
// ...

Why the grid needs filler

July 1, 2020 falls on a Wednesday, so the numbering starts in the Wednesday column and Monday and Tuesday of that first week would sit empty. The last day, July 31, is a Friday, leaving Saturday and Sunday of the final week empty. Those cells get filled with leading dates from the previous month and trailing dates from the next one, so the grid is always full.

Calendar grid showing the first two and last two days highlighted in red, indicated they are coming from the previous and next months.

Dates belonging to the selected month

Day.js's daysInMonth gives the number of days in the current month; a computed property wraps it.

// CalendarMonth.vue
computed: {
  // ...
  numberOfDaysInMonth() {
      return dayjs(this.selectedDate).daysInMonth();
  }
}

With that count, an empty array of matching length is created and map()ped into one day object per entry. The object structure is arbitrary — extra properties can be added as needed — but here it needs a date, used to test whether a given date is today, and an isCurrentMonth flag marking dates that fall outside the selected month so they can be styled accordingly.

// CalendarMonth.vue
computed: {
  // ...
  currentMonthDays() {
    return [...Array(this.numberOfDaysInMonth)].map((day, index) => {
      return {
        date: dayjs(`${this.year}-${this.month}-${index + 1}`).format("YYYY-MM-DD")
        isCurrentMonth: true
      };
    });
  },
}

Leading dates from the previous month

The starting point is the weekday of the first day of the selected month, found with the WeekDay plugin by way of a helper method.

// CalendarMonth.vue
methods: {
  // ...
  getWeekday(date) {
    return dayjs(date).weekday();
  },
}

Subtracting that weekday value from the first day of the current month yields the last Monday of the previous month — Wednesday means subtracting three days. That value gives both the number of days from the previous month that must appear and the starting point for an array of day objects running from that Monday through the end of the previous month.

// CalendarMonth.vue
computed: {
  // ...
  previousMonthDays() {
    const firstDayOfTheMonthWeekday = this.getWeekday(this.currentMonthDays[0].date);
    const previousMonth = dayjs(`${this.year}-${this.month}-01`).subtract(1, "month");

    // Cover first day of the month being sunday (firstDayOfTheMonthWeekday === 0)
    const visibleNumberOfDaysFromPreviousMonth = firstDayOfTheMonthWeekday ? firstDayOfTheMonthWeekday - 1 : 6;

    const previousMonthLastMondayDayOfMonth = dayjs(this.currentMonthDays[0].date).subtract(visibleNumberOfDaysFromPreviousMonth, "day").date();

    return [...Array(visibleNumberOfDaysFromPreviousMonth)].map((day, index) = {
      return {
        date: dayjs(`${previousMonth.year()}-${previousMonth.month() + 1}-${previousMonthLastMondayDayOfMonth + index}`).format("YYYY-MM-DD"),
        isCurrentMonth: false
      };
    });
  }
}

Trailing dates from the next month

The same helper serves in reverse. The count of days needed from the next month comes from subtracting the last day's weekday value from seven: a month ending on Saturday needs seven minus one, one day (Sunday).

// CalendarMonth.vue
computed: {
  // ...
  nextMonthDays() {
    const lastDayOfTheMonthWeekday = this.getWeekday(`${this.year}-${this.month}-${this.currentMonthDays.length}`);
    const nextMonth = dayjs(`${this.year}-${this.month}-01`).add(1, "month");
    const visibleNumberOfDaysFromNextMonth = lastDayOfTheMonthWeekday ? 7 - lastDayOfTheMonthWeekday : lastDayOfTheMonthWeekday;

    return [...Array(visibleNumberOfDaysFromNextMonth)].map((day, index) => {
      return {
        date: dayjs(`${nextMonth.year()}-${nextMonth.month() + 1}-${index + 1}`).format("YYYY-MM-DD"),
        isCurrentMonth: false
      };
    });
  }
}

All that remains is to merge the three sets into a single array holding every day the current month view shows, filler dates included.

// CalendarMonth.vue
computed: {
  // ...
  days() {
    return [
      ...this.previousMonthDays,
      ...this.currentMonthDays,
      ...this.nextMonthDays
    ];
  },
}