vue週間カレンダーコンポーネント

5277 ワード



// https://www.cnblogs.com/whitewen/articles/9509845.html
export default {
  name: 'week-date',
  data () {
    return {
      currentYear: 1970,
      currentMonth: 1,
      currentDay: 1,
      currentWeek: 1,
      days: [],
      weeks: ['   ', '   ', '   ', '   ', '   ', '   ', '   '],
      behindDate: '',
      frontDate: ''
    }
  },
  mounted () {

  },
  created () {
    this.initData(null)
  },

  methods: {
    formatDate (year, month, day) {
      const y = year
      let m = month
      if (m < 10) m = `0${m}`
      let d = day
      if (d < 10) d = `0${d}`
      return `${y}-${m}-${d}`
    },
    initData (cur) {
      let date = ''
      if (cur) {
        date = new Date(cur)
      } else {
        date = new Date()
      }
      //        
      this.currentDay = date.getDate()
      //     
      this.currentYear = date.getFullYear()
      //     
      this.currentMonth = date.getMonth() + 1
      this.currentWeek = date.getDay()
      // 1...6,0  //    
      if (this.currentWeek === 0) {
        this.currentWeek = 7
      }
      const str = this.formatDate(this.currentYear, this.currentMonth, this.currentDay)//       - - 
      this.days.length = 0
      //      ,      7   ,  6          ,         ,        i<= 35- this.currentWeek
      /* eslint-disabled */
      for (let i = this.currentWeek - 1; i >= 0; i -= 1) {
        const d = new Date(str)
        d.setDate(d.getDate() - i)
        this.days.push(d)
      }
      for (let i = 1; i <= 7 - this.currentWeek; i += 1) {
        const d = new Date(str)
        d.setDate(d.getDate() + i)
        this.days.push(d)
      }
      this.behindDate = this.formatDate(this.days[0].getFullYear(), this.days[0].getMonth() + 1, this.days[0].getDate())
      this.frontDate = this.formatDate(this.days[6].getFullYear(), this.days[6].getMonth() + 1, this.days[6].getDate())
    },
    //     
    weekPre () {
      //        7     7 
      const d = this.days[0]
      d.setDate(d.getDate() - 7)
      this.initData(d)
    },
    //     
    weekNext () {
      //        7     7 
      const d = this.days[6]
      d.setDate(d.getDate() + 7)
      this.initData(d)
    },
    //                
    pickPre (year, month) {
      const d = new Date(this.formatDate(year, month, 1))
      d.setDate(0)
      this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1))
    },
    //                
    pickNext (year, month) {
      const d = new Date(this.formatDate(year, month, 1))
      d.setDate(35)
      this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1))
    },
    //       
    pick (date) {
      alert(this.formatDate(date.getFullYear(), date.getMonth() + 1, date.getDate()))
    }
  }
}