localhost
localhost

Reputation: 861

vuejs mounted: Cannot set the value of undefined

I am trying to run the following function upon mounted but I get an error the

"Cannot set the property 'days' of undefined"

Following is my code

 function getDays(date) {
        this.days = (new Date()).getTime() / (1000 * 24 * 60 * 60);
        return parseInt(this.days) - this.START_DAYS;
  }

It is not helpful to tell which line is it. One of the reasons I did this.days is that VueJS had a problem for using let days

I am not much familiar with VueJS and how it accesses variable.

Upvotes: 0

Views: 380

Answers (2)

Ahmet Zeybek
Ahmet Zeybek

Reputation: 1224

You should create your getDays function in methods, then you can call it in mounted

I don't know why did you use date arg in getDays, but it wasn't used it in getDays method

...
data() {
  return {
    days: ''
    START_DAYS: ''
  }
}
methods: {
  getDays(date) {
    // 'date' is never used here ?
    this.days = (new Date()).getTime() / (1000 * 24 * 60 * 60);
    return parseInt(this.days) - this.START_DAYS;
  }
},
mounted() {
  this.getDays()
}
...

Upvotes: 1

Reinier68
Reinier68

Reputation: 3242

Did you declare your method this way? :

methods: {
    getDays(date) {
      this.days = new Date().getTime() / (1000 * 24 * 60 * 60);
      return parseInt(this.days) - this.START_DAYS;
    }
  },

Also, to call the method in mounted, use: this.getDays()

Check this codesandbox for clarification

Upvotes: 2

Related Questions