0

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"
2
  • 1
    You can access the Vue instance inside data() using this keyword. That's why it is giving the error. Try using computed properties. Commented Sep 3, 2022 at 10:46
  • 1
    @زوہیبخان You can, but it's incomplete, only props are available Commented Sep 3, 2022 at 13:19

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.