vant 日期选择器(年选、月选、周选、日选)

本文介绍了一个基于 Vant UI 框架的日期选择器组件实现方案,包括年、月、周和日的选择功能。该组件通过 ActionSheet 和 DateTimePicker 组件实现了丰富的日期选择体验,并使用 Moment.js 进行日期格式化处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vant 日期选择器(年选、月选、周选、日选)

        <van-field
            v-model="formatDate"
            is-link
            readonly
            arrow-direction="down"
            label="统计时间"
            placeholder="请选择统计时间"
            @click="dateSelect"
          />
          <van-action-sheet v-model="dateShow">
            <!-- 日/月选择器 -->
            <van-datetime-picker
              v-model="currentDate"
              :type="type"
              :title="dateTitle"
              :min-date="minDate"
              :max-date="maxDate"
              @confirm="confirm"
              @cancel="cancel"
            />
          </van-action-sheet>
          <!-- 周选择器 -->
          <van-action-sheet v-model="weekShow">
            <van-picker
              title="选择周数"
              show-toolbar
              :columns="columns"
              @cancel="cancel"
              @confirm="onConfirm"
            />
          </van-action-sheet>
          <!-- 年选择器 -->
          <van-action-sheet v-model="yearShow">
            <van-picker
              title="选择年"
              show-toolbar
              :columns="yearColumns"
              :default-index="yearSelect"
              @confirm="yearConfirm"
              @cancel="cancel"
            />
          </van-action-sheet>
import { postData } from "../api";
import { Toast } from "vant";
import moment from "moment";
import "moment/locale/zh-cn";
moment.locale("zh-cn");
// 获取一年的周次列表
const weelys = (y) => {
  const oneDay = moment(y + "-01-01");
  let oneWeely = null;
  if (oneDay.format("wo") == "1") {
    oneWeely = oneDay.startOf("week").format("YYYY-MM-DD");
  } else {
    // console.log("weeks");
    oneDay.add(1, "weeks");
    oneWeely = oneDay.startOf("week").format("YYYY-MM-DD");
  }
  const arr = [];
  let weelyStr = "1周";
  do {
    const d = {};
    let time = moment(oneWeely);
    d.value = time.format("YYYY-MM-DD");
    d.text = time.format("第wo");
    // +
    // "(" +
    // time.startOf("week").format("MM/DD") +
    // "-" +
    // time.endOf("week").format("MM/DD") +
    // ")";
    arr.push(d);
    oneDay.add(1, "weeks");
    oneWeely = oneDay.startOf("week").format("YYYY-MM-DD");
    weelyStr = oneDay.format("wo");
  } while (weelyStr != "1周" && oneWeely.indexOf(y) > -1);
  return arr;
};

export default {
  data() {
    return {
      type: "date",
      minDate: new Date(2000, 1, 1),
      maxDate: new Date(2060, 12, 31),
      currentDate: new Date(),

      loadShow: true,
      nullDataShow: false,
      message: "数据加载中...",

      objShow: false,
      rangShow: false,
      dateShow: false,
      formatDate: null,
      weekShow: false,
      yearShow: false,
      yearSelect: null,
      dateTitle: "",
      columns: [
        {
          values: [],
          className: "column1",
        },
        {
          values: [],
          className: "column2",
        },
      ],
      yearColumns: [2000, 2001, 2002],
      form: {
        objectType: null,
        collectcycle: null,
        reportDate: null,
      },

      objName: null,
      rangName: null,

      active: 0,
      tableData: [],
      reportList: [],
      reportList1: [],
      reportList2: [],
      URL: null,
    };
  },
  created() {
    this.setData();
    this.yearData();
  },

  methods: {
    // 监听统计范围
    dateSelect() {
      if (this.rangName == "日报" || this.rangName == "月报") {
        this.dateShow = true;
      } else if (this.rangName == "周报") {
        this.weekShow = true;
      } else if (this.rangName == "年报") {
        this.yearShow = true;
      } else {
        Toast.fail("请先选择统计范围");
      }
    },
    //周选择
    onConfirm(value) {
      const weeks = value[1].text.slice(1, -1);
      // console.log(weeks);
      if (weeks.length < 2) {
        this.form.reportDate = value[0] + "0" + weeks;
      } else {
        this.form.reportDate = value[0] + weeks;
      }
      this.formatDate = value[0] + "年" + value[1].text;

      this.weekShow = false;
    },
    //年选择器
    yearConfirm(value) {
      this.formatDate = value + "年";
      this.form.reportDate = value.toString();
      this.yearShow = false;
    },
    //日、月选择器
    confirm(value) {
      if (this.type == "date") {
        this.formatDate = value.format("yyyy年MM月dd日");
        this.form.reportDate = value.format("yyyyMMdd");
      } else if (this.type == "year-month") {
        this.formatDate = value.format("yyyy年MM月");
        this.form.reportDate = value.format("yyyyMM");
      }
      this.dateShow = false;
    },
    cancel() {
      this.dateShow = false;
      this.weekShow = false;
      this.yearShow = false;
    },


   


    //周选择器
    setData() {
      const defaultData = moment(this.defaults);
      let year = moment().format("YYYY");
      this.columns[0].values = [];
      for (let i = year - 10; i < year - 0 + 10; i++) {
        this.columns[0].values.unshift(i);
      }
      for (let i = 0; i < this.columns[0].values.length; i++) {
        if (this.columns[0].values[i] == year) {
          this.columns[0].defaultIndex = i;
          this.columns[0].valueKey = i;
          break;
        }
      }
      // console.log(this.columns);
      this.columns[1].values = weelys(year);
      for (let i = 0; i < this.columns[1].values.length; i++) {
        if (
          moment(this.columns[1].values[i].value).format("wo") ==
          defaultData.format("wo")
        ) {
          this.columns[1].defaultIndex = i;
          this.columns[1].valueKey = i;
          break;
        }
      }
    },
    //年数据 
    yearData() {
      for (let i = 2000; i < 2060; i++) {
        this.yearColumns.push(i);
      }
      //显示当前年份
      const year = new Date().format("yyyy");
      this.yearSelect = this.yearColumns.indexOf(Number(year));
    },
  },
};```
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210718124141238.PNG?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0NoYW5nZV94aWFv,size_16,color_FFFFFF,t_70#pic_center)

以下是基于vant组件库封装的时间择器到分钟的代码实例: ```vue <template> <van-popup v-model="showPicker" position="bottom"> <van-datetime-picker v-model="currentDate" type="datetime" :columns-order="columnsOrder" :formatter="formatter" :min-date="minDate" :max-date="maxDate" @confirm="onConfirm" @cancel="onCancel" /> </van-popup> </template> <script> export default { data() { return { showPicker: false, currentDate: new Date(), columnsOrder: ['year', 'month', 'day', 'hour', 'minute'], minDate: new Date(2000, 0, 1), maxDate: new Date(2030, 11, 31), }; }, methods: { formatter(type, value) { if (type === 'year') { return `${value}`; } else if (type === 'month') { return `${value}`; } else if (type === 'day') { return `${value}`; } else if (type === 'hour') { return `${value}时`; } else if (type === 'minute') { return `${value}分`; } return value; }, onConfirm(val) { this.showPicker = false; console.log(val); }, onCancel() { this.showPicker = false; }, showTimePicker() { this.showPicker = true; }, }, }; </script> ``` 在这个代码实例中,我们使用了vant组件库中的Popup弹出层组件和DatetimePicker时间择器组件。我们将DatetimePicker的type属性设置为datetime,同时将columnsOrder属性设置为['year', 'month', 'day', 'hour', 'minute'],这样就可以择到分钟了。我们还通过formatter属性对每个时间列进行了格式化,使其显示为中文的时分。最后,我们在onConfirm方法中打印出了择的时间值。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长夜将尽 来日可期

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值