使用dayjs,不懂的可以看一下
vue3使用dayjs以及dayjs日期工具类https://blog.csdn.net/weixin_45128657/article/details/136388537?spm=1001.2014.3001.5502
创建一个datePicker.vue组件
<template>
<el-date-picker v-model="state.dateTime" type="datetimerange" value-format="x" :range-separator="'至'"
style="width:355px;margin-right:5px;" :start-placeholder="'开始时间'" :end-placeholder="'结束时间'" @change="timeChange"/>
<el-button type="primary" @click="currentDayClick">今日</el-button>
<el-button type="primary" @click="yesterdayClick">昨日</el-button>
<el-button type="primary" @click="lastDayClick">上一日</el-button>
<el-button type="primary" @click="nextDayClick">下一日</el-button>
<el-button type="primary" @click="currentMonthClick">当月</el-button>
</template>
<script lang="ts" setup>
import dayjs from "dayjs"
const props = defineProps({
// 当天
datePicker: {
type: Array as any,
default: () => [],
},
})
const emit = defineEmits(['emitChange'])
const state = reactive({
dateTime: props.datePicker
})
// 今日
const currentDayClick = ()=>{
state.dateTime = []
emit('emitChange',state.dateTime)
}
// 昨日
const yesterdayClick = ()=>{
state.dateTime =[
dayjs().add(-1, 'day').startOf('day').valueOf(),
dayjs().add(-1, 'day').endOf('day').valueOf()
]
emit('emitChange',state.dateTime)
}
// 上一日
const lastDayClick = ()=>{
state.dateTime =[
dayjs(state.dateTime[0]).add(-1, 'day').startOf('day').valueOf(),
dayjs(state.dateTime[0]).add(-1, 'day').endOf('day').valueOf()
]
emit('emitChange',state.dateTime)
}
// 下一日
const nextDayClick = ()=>{
state.dateTime =[
dayjs(state.dateTime[1]).add(1, 'day').startOf('day').valueOf(),
dayjs(state.dateTime[1]).add(1, 'day').endOf('day').valueOf()
]
emit('emitChange',state.dateTime)
}
// 当月
const currentMonthClick = ()=>{
state.dateTime = [
dayjs().startOf('month').valueOf(),
dayjs().endOf('month').valueOf()
]
emit('emitChange',state.dateTime)
}
const timeChange = ()=>{
emit('emitChange',state.dateTime)
}
</script>
创建一个页面使用
<template>
<div class="my-layoutM20">
<el-card shadow="never" :body-style="{ paddingBottom: '10px' }">
<span class="fl" style="marginRight:10px">
<DatePicker :datePicker="state.datePicker" @emitChange="emitChange"/>
</span>
<el-button size="default" type="primary" @click="onQuery()">查询 </el-button>
</el-card>
</div>
</template>
<script lang="ts" setup>
import dayjs from 'dayjs'
const DatePicker = defineAsyncComponent(() => import('/@/components/search/datePicker.vue'))
const state:any = reactive({
datePicker:[
dayjs(new Date()).startOf('day').valueOf(),
dayjs(new Date()).endOf('day').valueOf()
],
})
// 时间日期change
const emitChange = (arr:any)=>{
state.datePicker = arr
}
const onQuery = () => {
console.log('日期:',state.datePicker)
}
</script>