Reputation: 19
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);
}
},
Upvotes: 0
Views: 252
Reputation: 138696
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);
}
}
}
Upvotes: 1