ElementUI2+Vue2实现日期选择长期功能

发布时间 2023-11-10 18:00:32作者: ASini

ElementUI2+Vue2实现日期选择长期功能

效果如图:

代码如下:

<template>
    <div>
      <el-row>
        <div class="block">
          <span class="demonstration">带快捷选项</span>
          <el-date-picker
            v-model="value2"
            :format="showDateMethod(this.value2)"
            value-format="yyyy-MM-dd"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </div>
      </el-row>
    </div>

</template>
<script>
export default {
  name: 'ElementView',
  data() {
      return {
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [
            {
            text: '长期',
            onClick(picker) {
              picker.$emit('pick', '9999-12-31');
            }
          }, 
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, 
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        value1: '',
        value2: ''
      }
    },
    methods:{
      showDateMethod(val){
          // 页面上展示的日期格式
        let result = 'yyyy 年 MM 月 dd 日'
        console.log(val)
        if(val === '9999-12-31'){
          result = '长期'
        }
        return result
      },
    }
}
</script>

要点:

  • 日期约定9999-12-31为长期日期
  • 在pickerOptions.shortcuts的集合中添加一个快捷选择
  • 使用format参数进行格式化显示

封装组件todo