[Vuejs]-VueJs: To Disable all dates up to specific date based on condition

0👍

sandbox

<template>
  <div id="app">
    Current date: {{ date }}
    <Datepicker v-if="date" :value="today" :disabled-dates="disabledDates"/>
  </div>
</template>

<script>
import Datepicker from "vuejs-datepicker/dist/vuejs-datepicker.esm.js";

export default {
  data() {
    return {
      today: new Date(),
      date: null,
      disabledDates: {}
    };
  },

  components: {
    Datepicker
  },

  methods: {
    // Utility: To get date by day
    // In our case to get last week friday & this week friday
    // first param: current date / any select date as reference
    // second param: day, in our case friday ie. 5
    // third param: week, in our case last week ie. -7 (7 days from now) & current week ie. 0
    getDateByDay(currDate, day, week = 0) {
      var reqDate = currDate;
      var reqDay = day - currDate.getDay() + week;
      reqDate.setDate(reqDate.getDate() + reqDay);
      return {
        day: reqDate.getDate(),
        month: reqDate.getMonth(),
        year: reqDate.getFullYear()
      };
    },

    // Strategy / logic to block on basis of monday / other days
    strategy({ year, month, day }) {
      this.date = new Date(year, month, day);
      let getDay = this.date.getDay();
      console.log({ getDay });

      // Check if monday ie. 0
      if (getDay === 1) {
        let { day, month, year } = this.getDateByDay(this.date, 6, -7 * 2);
        // Get last friday date & block upto last friday
        this.disabledDates.to = new Date(year, month, day);
      }

      // OTHER THAN MODAY
      else {
        let { day, month, year } = this.getDateByDay(this.date, 6, -7);
        // Get current friday & block uptp current friday
        this.disabledDates.to = new Date(year, month, day);
      }
    }
  },

  mounted() {
    // invoke blocking function with any date
    this.strategy({ year: 2020, month: 2, day: 25 });
  }
};
</script>

PS: You can modify logic as per your use case by passing desired params.

Leave a comment