Search code examples
javascripthtmlasp.netvue.jselement-ui

Access data's variable in other variable's function - undefined


I need to make an date validation in Vue depending on Vue models.

The problem is how this date validation works. I need to define variable in data segment which contains disabledDate function. So here is the simplified code:

Template:

<el-date-picker type="date"
  v-model="date1"
  :picker-options="datePickerOptions1">
</el-date-picker>

JS:

data() {
  return {
    date: null,
    rev: {
      validDate: null
    },
    datePickerOptions1: {
      disabledDate(date) {
        return date < this.rev.validDate;
      }
    }
  }
},
mounted: function() {
  var today = new Date();
  this.rev.validDate = today.getDate();
}

The console says this.rev.validDate is undefined.

In my case this.rev.validDate is fetched from database while component is mounted and depending on this that el-date-picker should work.

I would ask for any suggestions :)


Solution

  • The method disabledDate is deeply nested to where it loses the current Vue instance (otherwise accessible via this context). To work around this, you could assign the instance to a variable, like so:

    data() {
      const vm = this;
    
      return {
        date: null,
        rev: {
          validDate: null
        },
        datePickerOptions1: {
          disabledDate(date) {
            return date < vm.rev.validDate;
          }
        }
      }
    }
    

    Or with arrow function:

    data: vm => ({
      date: null,
      rev: {
        validDate: null
      },
      datePickerOptions1: {
        disabledDate(date) {
          return date < vm.rev.validDate;
        }
      }
    })