MathGainz
MathGainz

Reputation: 360

vue component data and computed properties

I am having the following issue.

I am declaring data and i want to setup before, current and day after.

data () {
  return {
    notes: {
      ...
    },
    view: {
      dayCurrent: new Date(),
      dayBefore: new Date().setDate(this.view.dayCurrent.getDate() - 1),
      dayAfter: new Date().setDate(this.view.dayCurrent.getDate() + 1)
    }
  }
}

But once I save this i am getting following error

Error in data(): "TypeError: Cannot read property 'dayCurrent' of undefined" as if my view object does not exist.

Why is this? How do I setup this and avoid this kind of error.

Upvotes: 1

Views: 59

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

I recommend to initialize your view property in mounted hook as follows :

data() {
    return {
      notes: {
        ...
      },
      view: {
        dayCurrent: '',
        dayBefore: '',
        dayAfter: ''
      }
    }
  },
  mounted() {
    this.view.dayCurrent = new Date();
    this.view.dayBefore = new Date(this.view.dayCurrent.getDate() - 1);

    this.view.dayAfter = new Date(this.view.dayCurrent.getDate() + 1)

  }

new Vue({
  el: '#app',

  data() {
    return {
      notes: {

      },
      view: {
        dayCurrent: '',
        dayBefore: '',
        dayAfter: ''
      }
    }
  },
  mounted() {
    this.view.dayCurrent = new Date();
    let d1 = new Date().setDate(this.view.dayCurrent.getDate() - 1);
    this.view.dayBefore = new Date(d1);
    let d2 = new Date().setDate(this.view.dayCurrent.getDate() + 1);
    this.view.dayAfter = new Date(d2)

  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{view.dayBefore}}</p>
  <p>{{view.dayCurrent}}</p>
  <p>{{view.dayAfter}}</p>
</div>

Upvotes: 2

Ana Liza Pandac
Ana Liza Pandac

Reputation: 4871

Another solution would be to declare dayCurrent outside the return statement and reference it in your other properties.

data () {
  const dayCurrent = new Date();
  return {
    notes: {
      ...
    },
    view: {
      dayCurrent: dayCurrent,
      dayBefore: new Date().setDate(dayCurrent.getDate() - 1),
      dayAfter: new Date().setDate(dayCurrent.getDate() + 1)
    }
  }
}

Upvotes: 5

Related Questions