最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - VueJS reactive Date object - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Apr 12, 2019 at 13:47 elvetielveti 2,3864 gold badges21 silver badges28 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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/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)
    }
  }
})
发布评论

评论列表(0)

  1. 暂无评论