简体   繁体   English

在 vue.js 中的方法中修改数据后手表不工作

[英]watch not working after data is modified in methods in vue.js

This is my code, watch is working once after beforeMount but when i am modifying newDate in methods it is not tracking the change.这是我的代码,watch 在 beforeMount 之后工作了一次,但是当我在方法中修改 newDate 时,它不会跟踪更改。

data() {
    return {
        time: ['12 AM', '1 AM', '2 AM', '3 AM', '4 AM', '5 AM', '6 AM', '7 AM', '8 AM', '9 AM', '10 AM', '11 AM', '12 PM'],
        newDate : '',
        formattedDate: '',
    };
},
watch: {
    newDate(newVal) {
        console.log(1);
        const year = newVal.getFullYear();
        const month = newVal.toLocaleString('default', { month: 'short'});
        const todayDate = String(newVal.getDate()).padStart(2,'0');
        this.formattedDate = `${month  }-${  todayDate  }-${  year}`;
    }
},
beforeMount() {
    this.newDate = new Date();
},
methods: {
    dateChange(action) {
        if(action==='prev') {
            this.newDate.setDate(this.newDate.getDate() -1);
        }
        else {
            this.newDate.setDate(this.newDate.getDate() +1);
        }
    },

The watcher isn't invoked because the newDate reference hasn't changed.由于newDate引用未更改,因此未调用观察程序。 dateChange() only modifies the same newDate . dateChange dateChange()仅修改相同的newDate

One solution is to reassign newDate to a new Date instance, which will cause the watcher to run:一种解决方案是将newDate重新分配给一个新的Date实例,这将导致观察者运行:

export default {
  methods: {
    dataChange(action) {
      let time = 0;
      if(action==='prev') {
        time = this.newDate.setDate(this.newDate.getDate() - 1);
      }
      else {
        time = this.newDate.setDate(this.newDate.getDate() + 1);
      }
      this.newDate = new Date(time);
    }
  }
}

demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM