4

Rather beginner question, but I couldn't find a solution anywhere.

I have 2 buttons that increment/decrement a given Date object by +/- 1 day. The object is updated, but the changes are not displayed. I found out it's because the Date Obj is not reactive, but I didn't find a solution or a workaround to this.

JSFiddle Demo

HTML:

<div id="app">
  <button @click="inc">+ 1 day</button>
  <button @click="dec">- 1 day</button>
  <br /><br />

  {{date}}
</div>

JS/Vue:

new Vue({
  el: "#app",
  data: {
    date: new Date()
  },
  methods: {
    inc () {
        this.date.setDate(this.date.getDate() + 1)
        console.log(this.date)
    },
    dec () {
        this.date.setDate(this.date.getDate() - 1)
        console.log(this.date)
    }
  }
})

In the console the Date is incresed/decreased fine, but the date rendered on the page just stays the same. Can anybody help with this? Thanks.

1 Answer 1

9

You are modifying the date object in place in which case Vue can not detect the changes, create a new date object instead:

https://jsfiddle.net/13gzu8xs/1/

new Vue({
  el: "#app",
  data: {
    date: new Date()
  },
  methods: {
    inc () {
      this.date.setDate(this.date.getDate() + 1)
      this.date = new Date(this.date)     //  create a new date and assign to this.date
        },
    dec () {
      this.date.setDate(this.date.getDate() - 1)
      this.date = new Date(this.date)
    }
  }
})
Sign up to request clarification or add additional context in comments.

1 Comment

Oooh, so simple. Thanks a lot, works like a charm and you saved me hours of trial & error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.