公司業務新開了一個商家管理微信H5移動端項目,日曆控件是商家管理員查看經過日程來篩選獲取某日用戶的訂單等數據。 如圖: 假設今天爲2018-09-02vue
90天前: node
90天后; ios
參考了基於Vue開發一個日曆組件 - 掘金日曆的年月日計算方式。 核心思想:假設當前月份是二月份,根據二月和三月的1號是星期幾,來對二月進行佈局。(若是須要在二月顯示一月和三月的日期,還須要知道一月份有多少天)vuex
在項目開發中,爲了與後臺同事並行開發。項目採用來mock模擬數據來攔截接口。express
// calendar.vue
<template>
<div class="cp-calendar">
<v-touch
@swipeleft="handleNextMonth"
@swiperight="handlePreMonth"
class="calendar">
<div class="calendar-main" >
<span class="item-con header-item"
v-for="(item, index) in calendarHeader"
:key="index">{{item}}</span>
<div :class="`item-con ${todayStyle(item.content) && 'item-con-today'} ${item.type === 'disabled' && 'disableStyle'}`"
:style="{opacity: isChangeMonth ? 0 : 1}"
@click.stop="handleDayClick(item)"
v-for="(item, index) in getMonthDays(selectedYear, selectedMonth)"
:key="item.type + item.content + `${index}`">
<span
:class="`main-content ${selectedDateStyle(item.content) && 'selectedColor'}`">
{{setContent(item.content)}}</span>
<span :class="`${selectedDateStyle(item.content) && 'item-con-point'}`" ></span>
</div>
</div>
</v-touch>
</div>
</template>
複製代碼
// calendar.vue
// 設置初始數據
initData () {
this.today = this.currentDate || getDateStr(0) // 若是沒有服務器時間,拿本地時間
this.prevDate = getDateStr(-90, this.currentDate)
this.nextDate = getDateStr(90, this.currentDate)
// 是否有手動選中的日期
let selectedFullDate = this.storeSelectedFullDate
if (!this.storeSelectedFullDate) {
selectedFullDate = this.currentDate || getDateStr(0) // 若是沒有服務器時間,拿本地時間
}
this.selectedYear = Number(selectedFullDate.split('-')[0])
this.selectedMonth = Number(selectedFullDate.split('-')[1]) - 1
this.selectedDate = Number(selectedFullDate.split('-')[2])
this.selectedFullDate = `${this.selectedYear}-${this.selectedMonth + 1}-${this.selectedDate}`
},
/ 渲染日期
getMonthDays(year, month) {
// 定義每一個月的天數,若是是閏年第二月改成29天
let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
daysInMonth[1] = 29;
}
// 當月第一天爲周幾
let targetDay = new Date(year, month, 1).getDay();
let calendarDateList = [];
let preNum = targetDay;
let nextNum = 0;
if (targetDay > 0) {
// 當前月份1號前的天然周剩餘日期,置空
for (let i = 0; i < preNum; i++) {
let obj = {
type: 'pre',
content: ''
};
calendarDateList.push(obj);
}
}
// 判斷當前年月份
let formatMonth = month + 1 >= 10 ? month + 1 : '0' + (month + 1)
this.prevYearMonthBoolean = (`${year}-${formatMonth}` === this.prevYearMonth)
this.nextYearMonthBoolean = (`${year}-${formatMonth}` === this.nextYearMonth)
for (let i = 0; i < daysInMonth[month]; i++) {
// 正常顯示的日期
let obj = {
type: 'normal',
content: i + 1
};
// 判斷是否爲最往前或者最日後的月份,篩選出不可點擊的日期
if (this.prevYearMonthBoolean) {
let prevDay = this.prevDate.split('-')[2]
if (i + 1 < prevDay) {
obj.type = 'disabled'
}
} else if (this.nextYearMonthBoolean) {
let nextDay = this.nextDate.split('-')[2]
if (i + 1 > nextDay) {
obj.type = 'disabled'
}
}
calendarDateList.push(obj);
}
nextNum = 6 - new Date(year, month + 1, 0).getDay()
// 當前月份最後一天的天然周剩餘日期,置空
for (let i = 0; i < nextNum; i++) {
let obj = {
type: 'next',
content: ''
};
calendarDateList.push(obj);
}
return calendarDateList;
},
// 設置日期
setContent (content) {
if (!content) return ''
return `${this.selectedYear}-${this.tf(this.selectedMonth + 1)}-${this.tf(content)}` === this.today ? '今天' : content
},
// '今天'樣式開關
todayStyle (content) {
if (!content) return false
// Toast(`${this.selectedYear}-${this.tf(this.selectedMonth + 1)}-${this.tf(content)}`)
return `${this.selectedYear}-${this.tf(this.selectedMonth + 1)}-${this.tf(content)}` === this.today
},
// 當前選中的日期樣式開關
selectedDateStyle (content) {
if (!content) return false
return `${this.selectedYear}-${this.selectedMonth + 1}-${content}` === this.selectedFullDate
},
複製代碼
// src/config/utils.js
// 公共方法
/**
* @param AddDayCount 必傳 今天先後N天的日期
* @param dateStr: 非必傳 獲取傳入日期先後N天的日期:'2018-01-20'
* @param type 非必傳 'lhRili'類型格式如'2018-7-3'
* @return 返回日期'2018/01/20'
*/
export const getDateStr = (AddDayCount, dateStr, type) => {
// console.log('getDateStr', AddDayCount, dateStr, type)
var dd
if (!dateStr) {
dd = new Date()
} else {
// 判斷是否爲IOS
const isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
let formatDateStr = isIOS ? dateStr.replace(/-/g, '/') : dateStr
dd = new Date((formatDateStr.length < 12) ? formatDateStr + ' 00:00:00' : formatDateStr)
}
dd.setDate(dd.getDate() + AddDayCount) // 獲取AddDayCount天后的日期
let y = dd.getFullYear()
let m
let d
if (type === 'lhRili') {
m = dd.getMonth() + 1
d = dd.getDate()
} else {
let currentMon = (dd.getMonth() + 1)
let getDate = dd.getDate()
m = currentMon < 10 ? '0' + currentMon : currentMon // 獲取當前月份的日期,不足10補0
d = getDate < 10 ? '0' + getDate : getDate // 獲取當前幾號,不足10補0
}
let time = y + '-' + m + '-' + d
return time
}
複製代碼
// calendar.vue
// 上一個月
handlePreMonth() {
if (this.prevYearMonthBoolean) {
return
}
if (this.selectedMonth === 0) {
this.selectedYear = this.selectedYear - 1
this.selectedMonth = 11
this.selectedDate = 1
} else {
this.selectedMonth = this.selectedMonth - 1
this.selectedDate = 1
}
},
// 下一個月
handleNextMonth() {
if (this.nextYearMonthBoolean) {
return
}
if (this.selectedMonth === 11) {
this.selectedYear = this.selectedYear + 1
this.selectedMonth = 0
this.selectedDate = 1
} else {
this.selectedMonth = this.selectedMonth + 1
this.selectedDate = 1
}
},
複製代碼
// src/store/schedule.js
const schedule = {
state: {
selectedDate: '', // 手動點擊選中的日期
currentDate: '' // 服務器當前日期
},
getters: {
getSelectedDate: state => state.selectedDate,
getCurrentDate: state => state.currentDate
},
mutations: {
SET_SELECTED_DATE: (state, data) => {
state.selectedDate = data
},
SET_CURRENT_DATE: (state, data) => {
state.currentDate = data
}
},
actions: {
setSelectedDate: ({ commit }, data) => commit('SET_SELECTED_DATE', data),
setCurrentDate: ({ commit }, data) => commit('SET_CURRENT_DATE', data)
}
};
export default schedule;
複製代碼
// src/directive/click-out-side.js
export default{
bind (el, binding, vnode) {
function documentHandler (e) {
if (el.contains(e.target)) {
return false;
}
if (binding.expression) {
binding.value(e);
}
}
el.__vueClickOutside__ = documentHandler;
document.addEventListener('click', documentHandler);
},
unbind (el, binding) {
document.removeEventListener('click', el.__vueClickOutside__);
delete el.__vueClickOutside__;
}
}
複製代碼
註冊指令瀏覽器
// src/directive/index.js
import clickOutSide from './click-out-side'
const install = function (Vue) {
Vue.directive('click-outside', clickOutSide)
}
if (window.Vue) {
window.clickOutSide = clickOutSide
Vue.use(install); // eslint-disable-line
}
clickOutSide.install = install
export default clickOutSide
複製代碼
// src/main.js
import clickOutSide from '@/directive/click-out-side/index'
Vue.use(clickOutSide)
複製代碼
使用方式:當某節點外部須要觸發事件時,掛載到該節點上bash
// calendar.vue
<div class="cp-calendar" v-click-outside="spaceClick">
....
</div>
複製代碼
這裏須要使用fastclick
庫來消除解決移動端點擊事件300ms延時服務器
// src/mian.js
import FastClick from 'fastclick' // 在移動端,手指點擊一個元素,會通過:touchstart --> touchmove -> touchend --> click。
FastClick.attach(document.body);
複製代碼
// src/mock/index.js
// mock數據入口
import Mock from 'mockjs'
import currentTime from './currentTime'
// 攔截接口請求
Mock.mock(/\/schedule\/getCurrentTime/, 'get', currentTime)
export default Mock
複製代碼
// src/mock/currentTime.js
import Mock from 'mockjs'
export default {
getList: () => {
return {
'status': 'true',
'code': '200',
'msg': null,
'info': {
'currentDate': '2018-09-02'
}
}
}
}
複製代碼
// src/main.js
// 開發環境引入mock
if (process.env.NODE_ENV === 'development') {
require('./mock') // 須要在這裏引入mock數據才能夠全局攔截請求
}
複製代碼