簡體   English   中英

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

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

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

由於newDate引用未更改,因此未調用觀察程序。 dateChange 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);
    }
  }
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM