简体   繁体   中英

VueJS Calendar go back and forth one month

I have build a calendar that shows a table of dates and the corresponding day, and i want to add the function to change between months. The Method i have made here does "work". It goes back a month when i click a button that takes this function. but only once, and this is because the selectedDate does not update, so when i try to debug using the console.log(selectedDate) that i commented out it still prints todays date.. Hope someone can help me out here

methods: {
  prevMonth() {
    var selectedDate = moment(new Date());
    let futureMonth = moment(selectedDate.subtract(1, 'month')).startOf('month')
        selectedDate = futureMonth;
    //return console.log(selectedDate)
    this.days = [...Array(futureMonth.daysInMonth())].map((_, i) => {
      return {
        date: futureMonth.clone().add(i, "day"),
        workhours: Math.floor(Math.random()*10),
        overtime: Math.floor(Math.random()*10),
        flextime: 0,
        sickness: 0,
        vacation: 0,
      }

    })
  }
}

You set the selectedDate to moment(new Date()) every time you run this method. So it always goes back one month based on today.

You need to keep the state of selectedDate, something like this should work:

data() {
  return {
    selectedDate: undefined
  }
},
mounted() {
  this.selectedDate = moment(new Date())
},
methods: {
  prevMonth() {
    let futureMonth = moment(this.selectedDate.subtract(1, 'month')).startOf('month')
    this.selectedDate = futureMonth;
    ......
    })
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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