vue3+vant4 encapsulates date and time components (year, month, day, hour, minute and second)

Vant4 currently cannot directly use the year, month, day, hour, minute and second components that come with vant3. After comprehensive consideration, I decided to package one myself!

vue3 + vant4 encapsulates date and time components (year, month, day, hour, minute and second)

  • renderings
  • code segment
    • Core component code
    • introduce

Renderings

Code snippet

Core component code

<template>
  <!-- Pop-up layer -->
  <van-popup v-model:show="data.isPicker" position="bottom" round @close="confirmOn">
    <van-picker ref="picker" title="Please select a time" :columns="data.columns" @change="onChange" @cancel="cancelOn"
      @confirm="onConfirm" v-model="data.selectedValues" />
  </van-popup>
</template>
<script setup>

import {<!-- --> reactive, watch, getCurrentInstance } from "vue";

const customFieldName = {<!-- -->
  text: "value",
  value: "values",
  children: ""
};
const data = reactive({<!-- -->
  isPicker: false, //Whether to display the pop-up layer
  columns: [], //All time columns
  selectedValues: [] //The time value selected by the control
});

const props = defineProps({<!-- -->
  //Incoming development status
  showPicker: {<!-- -->
    type: Boolean
  },
  //The value passed in
  values: {<!-- -->
    type: String
  }
});

//Define events to be passed to the parent component
const emit = defineEmits(["changeValue", "confirm"]);


watch(
  () => props.showPicker,
  val => {<!-- -->
    data.isPicker = val;
    data.columns = [];
    getcolumns();
  },
  {<!-- -->
    immediate: true//Monitor immediately--it will be executed once when entering to monitor the development status.
  }
);


function onChange() {<!-- -->
  // Useless method
}


function getcolumns() {<!-- -->
  let strtime = props.values; //The time passed in
  //console.log(strtime); 2023-09-05 19:28:00
  let date = new Date(strtime.replace(/-/g, "/"));
  // console.log(date); Wed Aug 09 2023 14:53:15 GMT + 0800 (China Standard Time)
  let timeVaules = date.getTime();

  let dateVaules;
  if (props.values != "") {<!-- -->
    dateVaules = new Date(timeVaules);
  } else {<!-- -->
    dateVaules = new Date(); //If no time is passed in, the current time will be defaulted
  }

  let Y = dateVaules.getFullYear();
  let M = dateVaules.getMonth();
  let D = dateVaules.getDate();
  let h = dateVaules.getHours();
  let m = dateVaules.getMinutes();
  let s = dateVaules.getSeconds();

  let year = []; //Get the array of ten years before and after
  year.values = [];
  let Currentday = new Date().getFullYear();
  for (let i = Currentday - 10; i < Currentday + 10; i + + ) {<!-- -->
    year.push({<!-- --> text: i.toString(), value: i });
  }
  year.defaultIndex = year.values.indexOf(Y); //Set the default option for the current year

  //Fill the single digit with 0
  const _M = M < 10 ? `0${<!-- -->M + 1}` : M.toString(); //The month is 1 less than the actual one, so add 1
  const _D = D < 10 ? `0${<!-- -->D}` : D.toString();
  const _h = h < 10 ? `0${<!-- -->h}` : h.toString();
  const _m = m < 10 ? `0${<!-- -->m}` : m.toString();
  const _s = s < 10 ? `0${<!-- -->s}` : s.toString();

  // Generate year, month, day, hour, minute and second time value
  data.selectedValues.push(Y);
  data.selectedValues.push(_M);
  data.selectedValues.push(_D);
  data.selectedValues.push(_h);
  data.selectedValues.push(_m);
  data.selectedValues.push(_s);

  data.columns.push(year); //Generate year column

  let month = []; //Get the December array
  month = Object.keys(Array.apply(null, {<!-- --> length: 13 })).map(function (item) {<!-- -->
    if ( + item + 1 <= 10) {<!-- -->
      return {<!-- --> text: "0" + item, value: "0" + item };
    } else if ( + item + 1 == 11) {<!-- -->
      return {<!-- --> text: + item, value: + item };
    } else {<!-- -->
      return {<!-- -->
        text: ( + item + 0).toString(),
        value: ( + item + 0).toString()
      };
    }
  });
  month.splice(0, 1);
  data.columns.push(month); //Generate month column

  //Get the number of days in the current month
  let days = getCountDays(Y, M + 1);
  let day = []; //Create an array of days of the month
  day = Object.keys(Array.apply(null, {<!-- --> length: days + 1 })).map(function (
    item
  ) {<!-- -->
    if ( + item + 1 <= 10) {<!-- -->
      return {<!-- --> text: "0" + item, value: "0" + item };
    } else if ( + item + 1 == 11) {<!-- -->
      return {<!-- --> text: + item, value: + item };
    } else {<!-- -->
      return {<!-- -->
        text: ( + item + 0).toString(),
        value: ( + item + 0).toString()
      };
    }
  });
  day.splice(0, 1);
  data.columns.push(day); //Generate day column

  let hour = []; //Create hour array
  hour = Object.keys(Array.apply(null, {<!-- --> length: 24 })).map(function (item) {<!-- -->
    if ( + item + 1 <= 10) {<!-- -->
      return {<!-- --> text: "0" + item, value: "0" + item };
    } else if ( + item + 1 == 11) {<!-- -->
      return {<!-- --> text: + item, value: + item };
    } else {<!-- -->
      return {<!-- -->
        text: ( + item + 0).toString(),
        value: ( + item + 0).toString()
      };
    }
  });
  data.columns.push(hour); //Generate hour column

  let mi = []; //Create minutes array
  mi = Object.keys(Array.apply(null, {<!-- --> length: 60 })).map(function (item) {<!-- -->
    if ( + item + 1 <= 10) {<!-- -->
      return {<!-- --> text: "0" + item, value: "0" + item };
    } else if ( + item + 1 == 11) {<!-- -->
      return {<!-- --> text: + item, value: + item };
    } else {<!-- -->
      return {<!-- -->
        text: ( + item + 0).toString(),
        value: ( + item + 0).toString()
      };
    }
  });
  data.columns.push(mi);//Generate minute column

  let ss = []; //Create seconds array
  ss = Object.keys(Array.apply(null, {<!-- --> length: 60 })).map(function (item) {<!-- -->
    if ( + item + 1 <= 10) {<!-- -->
      return {<!-- --> text: "0" + item, value: "0" + item };
    } else if ( + item + 1 == 11) {<!-- -->
      return {<!-- --> text: + item, value: + item };
    } else {<!-- -->
      return {<!-- -->
        text: ( + item + 0).toString(),
        value: ( + item + 0).toString()
      };
    }
  });
  data.columns.push(ss);//Generate seconds column
}


function getCountDays(year, month) {<!-- -->
  //Get the number of days in a certain year and month
  let day = new Date(year, month, 0);
  return day.getDate();
}

// Close the pop-up box
function confirmOn() {<!-- -->
  emit("changeValue");
}


//The time selector is closed, the value does not change and the pop-up box is closed.
function cancelOn({<!-- --> selectedValues }) {<!-- -->
  confirmOn()
}

// Time selector determines value change
function onConfirm({<!-- --> selectedValues }) {<!-- -->
  let endval =
    selectedValues[0] +
    "-" +
    selectedValues[1] +
    "-" +
    selectedValues[2] +
    " " +
    selectedValues[3] +
    ":" +
    selectedValues[4] +
    ":" +
    selectedValues[5];

  confirmOn()
  emit("confirm", endval);
}
</script>


Introduction

import DataTime from "@/components/datatime/index.vue";
...
const startTime = ref(""); //Value definition
const showPicker = ref(false); //Show and hide the pop-up box

const onConfirm = selectedValues => {<!-- -->
  //console.log(selectedValues);
  //2023-09-08 19:01:37
  startTime.value = selectedValues;
  showPicker.value = false;
};

 <DataTime
   :values="endTime"
    @changeValue="showPicker = false" //Subcomponent method
    :showPicker="showPicker"
    @confirm="onConfirm" //Subcomponent method
  />
  ...