Home > Enterprise >  Variable from data is undefined in methods
Variable from data is undefined in methods

Time:09-04

I have two variables in data: date_current anddays. And I have days_getmethod which returns all days in current month. I want to define days variable as days: this.days_get() but I get error which tells me that date_current is undefined.

But if I move definition of days into beforeMount hook all works fine.

Can I define days in data?

Full component code:

<template>
  <div></div>
</template>

<script>
export default {
  name: "Calendar",

  data(){
    return {
      date_current: new Date(),
      days: this.days_get()
    }
  },


  methods: {
    days_get(){
      const date_iteration = new Date(this.date_current.getFullYear(), this.date_current.getMonth())
      let days = []

      while(date_iteration.getMonth() === this.date_current.getMonth()){
        days.push(new Date(date_iteration.getFullYear(), date_iteration.getMonth(), date_iteration.getDate()))

        date_iteration.setDate(date_iteration.getDate()   1)
      }

      return days
    }
  }

}
</script>

<style scoped></style>

Error:

[Vue warn]: Error in data(): "TypeError: this.date_current is undefined"

CodePudding user response:

Well its exactly like you said: when you call days_get within data() then date_current is not yet defined (this happens after data). beforeMounted comes after data so there it would work because then you defined date_current. But even better would be to use a computed property:

<template>
  <div></div>
</template>

<script>
export default {
  name: "Calendar",

  data(){
    return {
      date_current: new Date()
    }
  },


  computed: {
    days(){
      const date_iteration = new Date(this.date_current.getFullYear(), this.date_current.getMonth())
      let days = []

      while(date_iteration.getMonth() === this.date_current.getMonth()){
        days.push(new Date(date_iteration.getFullYear(), date_iteration.getMonth(), date_iteration.getDate()))

        date_iteration.setDate(date_iteration.getDate()   1)
      }

      return days
    }
  }

}
</script>

<style scoped></style>
  • Related