Search code examples
vue.jsvuejs2vue-clivue-cli-3

Vuejs: how to implement reactively disable datepicker


im newbie here. I want control the datepicker to be disabled automatically based on the existing api. I using the vuejs-datepicker library. I've seen the documentation and managed to implement it statically, but having problems when implementing it reactively.

This is my previous view:

<datepicker 
    :disabled-dates="state.disabledDates">
</datepicker>

And, my previous static value of datepicker, especially for the day:

data() {
    var year = (new Date()).getFullYear()
    var month = (new Date()).getMonth()
    var dDate = (new Date()).getDate()
    
    var state = {
        disabledDates: {
            to: new Date(year, month, dDate), // Disable all dates up to specific date
            // from: new Date(2020, 0, 26), // Disable all dates after specific date
            days: [0,1], // Disable Saturday's and Sunday's
        }
    }
    return {
        
        state: state,

        day: '',        
    }
},

For now, here my view:

<datepicker 
    :disabled-dates="disabledDates">
</datepicker>

Console output:

enter image description here

My script:

<script>
data() {
    return {
        day: '',

        year : (new Date()).getFullYear(),
        month : (new Date()).getMonth(),
        dDate : (new Date()).getDate(),
        
    }
},
computed:{
    // reactive
    disabledDates: {
        to: new Date(year, month, dDate), // Disable all dates up to specific date, 2020,8,8
        days: [day], // Disable day, 0,1
    }  
},
watch: {
    'day': function(day){
        console.log('day: '+day)
        return this.day
    },
},
</script>

Thank you.


Solution

  • I'm pretty sure your only problem is that your syntax for computed properties is wrong. They should be functions, since they need to be run. Their dependencies are automatically determined by Vue, and when those change, the function is re-run. So, try this:

    data: function() {
      return {
        day: '',
        year: (new Date()).getFullYear(),
        month: (new Date()).getMonth(),
        dDate: (new Date()).getDate()
      };
    },
    computed: {
      // Here. This should be a function.
      disabledDates: function() {
        return {
          // Make sure to use 'this.' when in a component
          to: new Date(this.year, this.month, this.dDate),
          days: [ this.day ]
        };
      }
    },
    watch: {
      day: function(day) {
        console.log(`Day: ${day}`);
        return value;
      }
    }