0

This is my code, watch is working once after beforeMount but when i am modifying newDate in methods it is not tracking the change.

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);
        }
    },

1 Answer 1

1

The watcher isn't invoked because the newDate reference hasn't changed. dateChange() only modifies the same newDate.

One solution is to reassign newDate to a new Date instance, which will cause the watcher to run:

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

Sign up to request clarification or add additional context in comments.

Comments

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.