Vue3组件(六)封装一下日期组件

简介: UI库的日期组件嘛,还是很强大的,稍微封装一下就好,主要还是为了可以统一接口。

UI库的日期组件嘛,还是很强大的,稍微封装一下就好,主要还是为了可以统一接口。


日期的几种变化



日期组件又可以细分为一下几种:


  • 日期
  • 日期+时间
  • 年月
  • 年周


我们可以设置几个字典来区分一下。


// 类型的字典
const dateType = {
  100: 'dates/datetimerange/daterange/monthrange',
  110: 'date',
  111: 'datetime',
  114: 'month',
  115: 'week',
  116: 'year'
}
// 根据类型设置宽度
const style = {
  110: { // date
    width: '160px'
  },
  111: { // datetime
    width: '190px'
  },
  114: { // month
    width: '140px'
  },
  115: { // week
    width: '140px'
  },
  116: { // year
    width: '140px'
  }
}
// 根据类型设置显示用的format
const format = {
  110: 'YYYY-MM-DD',
  111: 'YYYY-MM-DD HH:mm:ss',
  114: 'gggg年 MM月',
  115: 'gggg 第ww周',
  116: 'gggg 年'
}
复制代码


然后在做个管理类。


/**
 * 日期管理类
 * * 功能:
 * ** 按照类型提交数据,不是date()
 * ** 监听属性,设置value
 * * 参数:
 * ** value: control类的value
 * ** mySubmit: control类的mySubmit,直接就提交了
 * ** controlType:属性里的控件类型
 * * 返回
 * ** 绑定控件的 mydate
 * ** change 事件的 myChange
 */
const dateManage = (value, mySubmit, controlType, controlId) => {
  // 日期控件用的v-model,便于做类型转换
  const mydate = ref(new Date(value.value))
  if (controlType === 115) {
    // 把周数转换成日期
    const arr = value.value.split('w')
    if (arr.length > 1) {
      mydate.value = new Date(new Date(arr[0] + '-1-1').valueOf() + arr[1] * 7 * 24 * 3600000)
    }
  }
  // 监听属性,设置给 mydate
  watch(() => value.value, (v1, v2) => {
    if (controlType === 115) {
      // 把周数转换成日期
      const arr = v1.split('w')
      if (arr.length > 1) {
        // mydate.value = new Date(new Date(arr[0] + '-1-1').valueOf() + (arr[1] - 1) * 7 * 24 * 3600000)
      }
    } else {
      mydate.value = new Date(v1)
    }
  })
  // 向父组件提交数据。
  const myChange = (_val) => {
    const val = _val
    const year = val.getFullYear()
    const month = (val.getMonth() + 1).toString().padStart(2, '0')
    const day = val.getDate().toString().padStart(2, '0')
    const hour = val.getHours().toString().padStart(2, '0')
    const mm = val.getMinutes().toString().padStart(2, '0')
    const ss = val.getSeconds().toString().padStart(2, '0')
    let re = ''
    switch (controlType) {
      case 110: // 日期
        re = `${year}-${month}-${day}`
        break
      case 111:
        re = `${year}-${month}-${day} ${hour}:${mm}:${ss}`
        break
      case 114:
        re = `${year}-${month}`
        break
      case 115: // 直接去dom找。没发现更好的方法
        setTimeout(() => {
          re = document.getElementsByName('c' + controlId)[0].value
          console.log('周1:', re)
          re = re.replace(' 第', 'w').replace('周', '')
          console.log('周2:', re)
          mySubmit(re) // 提交给父组件
        }, 500)
        break
      case 116:
        re = year
        break
    }
    console.log('日期控件值:', val, controlType)
    mySubmit(re) // 提交给父组件
  }
  return {
    mydate,
    myChange
  }
}
复制代码


主要就是依据类型做一下具体的处理。 UI库的日期组件返回的是标准的Date(),这个好像没啥,只是不管是年月类型,还是年周类型,都是返回date。 另外date在变成 json 的时候会自动变成这样的形式: 2020-06-24T16:06:26.860Z,这个好像有个时区的问题。


返回数据的处理



然后我就想,能不能简单一点, 日期的就返回“2020-06-04”, 年月的就返回“2020-06” 年周的返回“2020w20”


这样是不是很简单明了。 后端接收到也可以做相应的处理。


我个人是喜欢这种简单粗暴的方式。 当然如果不喜欢,可以换成date的类型。


获取第几周的数据时好顿折腾,很奇怪为啥没有直接给第几周,而是还要自己想办法,查了半天,找到一个获取dom然后去value的方式,真的挺无语的。


组件代码



<el-date-picker :style="style[meta.controlType]"
    v-model="mydate"
    :type="dateType[meta.controlType]"
    @change="myChange"
    :id="'c' + meta.controlId"
    :name="'c' + meta.controlId"
    :disabled="meta.disabled"
    :readonly="meta.readonly"
    :placeholder="meta.placeholder"
    :autofocus="meta.autofocus"
    :format="format[meta.controlType]"
  >
  </el-date-picker>
复制代码


id好像被吃掉了,没有给设置上,好郁闷。


import controlManage from '../manage/controlManage.js'
import { metaInput } from '../manage/config.js'
import { ref, watch } from 'vue'
export default {
  name: 'nf-el-from-date',
  props: {
    modelValue: String,
    meta: metaInput
  },
  emits: ['change', 'blur', 'focus'],
  setup (props, context) {
    const { value, mySubmit } = controlManage(props, context)
    return {
      ...dateManage(value, mySubmit, props.meta.controlType, props.meta.controlId),
      dateType, // 类型:日期、日期时间、年月、年周
      format, // 格式化
      style // 控制宽度
    }
  }
}
复制代码


这里就简单了,引入js,然后组合一下就好。


效果



image.png


时间组件



这个就比较简单了。UI库分成了两类,一个是选择固定选项的,一个是任意时间的。两个都挺简单的。


挺无语的,TimePicker 返回的是 date(),而TimeSelect 返回的是‘8:15’ 这样的。既然都是时间控件,返回数据的格式应该统一一下吧。


那么我们来统一好了,还是简单粗暴的方式,返回时间部分。


image.png


image.png


统一了,就方便多了。


附上代码。


<!--日期-->
<template>
  <el-time-picker v-if="meta.controlType === 112"
    style="width:130px;"
    v-model="mytime"
    @change="myChange"
    :id="'c' + meta.controlId"
    :name="'c' + meta.controlId"
    :disabled="meta.disabled"
    :readonly="meta.readonly"
    :placeholder="meta.placeholder"
  >
  </el-time-picker>
  <el-time-select  v-if="meta.controlType === 113"
    style="width:100px;"
    v-model="mytime"
    @change="myChange"
    :id="'c' + meta.controlId"
    :name="'c' + meta.controlId"
    :disabled="meta.disabled"
    :readonly="meta.readonly"
    :placeholder="meta.placeholder"
  >
</el-time-select>
</template>
复制代码


<script>
import controlManage from '../manage/controlManage.js'
import { metaInput } from '../manage/config.js'
import { ref, watch } from 'vue'
/**
 * 日期管理类
 * * 功能:
 * ** 按照类型提交数据,不是date()
 * ** 监听属性,设置value
 * * 参数:
 * ** value: control类的value
 * ** mySubmit: control类的mySubmit,直接就提交了
 * ** controlType:属性里的控件类型
 * * 返回
 * ** 绑定控件的 mydate
 * ** change 事件的 myChange
 */
const timeManage = (value, mySubmit, controlType) => {
  // 日期控件用的v-model,便于做类型转换
  const mytime = ref(new Date('1900-1-1 00:00:00'))
  if (value.value !== null) {
    // mytime.value = new Date('1900-1-1 ' + value.value)
  }
  // 监听属性,设置给 mydate
  watch(() => value.value, (v1, v2) => {
    if (controlType === 112) {
      // 把周数转换成日期
      mytime.value = new Date('1900-1-1 ' + v1)
    } else {
      // mytime.value = new Date(v1)
    }
  })
  // 向父组件提交数据。
  const myChange = (_val) => {
    const val = _val
    if (controlType === 112) {
      const hour = val.getHours().toString().padStart(2, '0')
      const mm = val.getMinutes().toString().padStart(2, '0')
      const ss = val.getSeconds().toString().padStart(2, '0')
      const re = `${hour}:${mm}:${ss}`
      mySubmit(re) // 提交给父组件
    } else {
      mySubmit(val) // 提交给父组件
    }
    console.log('日期控件值:', val, controlType)
  }
  return {
    mytime,
    myChange
  }
}
export default {
  name: 'nf-el-from-time',
  props: {
    modelValue: Object,
    meta: metaInput
  },
  emits: ['change', 'blur', 'focus'],
  setup (props, context) {
    const { value, mySubmit } = controlManage(props, context)
    const { mytime, myChange } = timeManage(value, mySubmit, props.meta.controlType)
    return {
      mytime,
      myChange
    }
  }
}
</script>
复制代码


在内部做了一下类型判断,代码和date的很像,因为只有时间类型,所以判断上就简单多了。


源码



github.com/naturefwvue…



相关文章
|
1天前
|
存储 API
vue3中如何动态自定义创建组件并挂载
vue3中如何动态自定义创建组件并挂载
|
1天前
|
JavaScript
vue 函数化组件
vue 函数化组件
|
6天前
|
JavaScript 调度
Vue3 使用 Event Bus
Vue3 使用 Event Bus
11 1
|
6天前
|
JavaScript
Vue3 : ref 与 reactive
Vue3 : ref 与 reactive
9 1
|
6天前
|
JavaScript
Vue组件传值异步问题--子组件拿到数据较慢
Vue组件传值异步问题--子组件拿到数据较慢
11 0
|
6天前
Vue3 使用mapState
Vue3 使用mapState
10 0
|
2天前
|
JavaScript
vue中watch的用法
vue中watch的用法
|
2天前
|
JavaScript 前端开发
vue动态添加style样式
vue动态添加style样式
|
2天前
|
JavaScript 前端开发
Vue项目使用px2rem
Vue项目使用px2rem
|
1天前
|
JavaScript API
vue学习(13)监视属性
vue学习(13)监视属性
10 2