【问题标题】:watch not working after data is modified in methods in vue.js在 vue.js 中的方法中修改数据后手表不起作用
【发布时间】:2021-05-28 14:16:01
【问题描述】:

这是我的代码,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);
        }
    },

【问题讨论】:

    标签: javascript vue.js frontend


    【解决方案1】:

    观察者没有被调用,因为newDate 引用没有改变。 dateChange() 只修改相同的newDate

    一种解决方案是将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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 2023-03-15
      • 2019-03-13
      • 1970-01-01
      • 2018-09-09
      • 2017-06-22
      • 2021-11-25
      相关资源
      最近更新 更多