Vue3.0封装日期格式化管道(过滤器)函数

前言:

最近这段时间,公司更新技术栈,逐步从原来的angular转移到了当前比较火的vue3.0上来,以下代码均是基于Vue3.0+ant+TypeScript+Vite+less环境进行开发的

vue3.0简介

这里就不做过多叙述了,有需要的可以去官网vue3.0看这里

vue3.0过滤器(filter)

有关叙述和部分案例可以看这里vue3.0关于filter的描述
从官网上的描述,我们可以看出,我们如果使用全局的filter来添加过滤器其实已经没有太多必要,它已经不再像2.0时期可以使用管道符(|)来对数据进行格式化,反而使用变成了一个方法的调用,因此我们完全可以用一个公共方法来代替上面的写法,下面看下我的代码吧

const DateFormatPipe = (date: Date, type: String) => {
    
    
    if (date) {
    
    
      let year, month, day, HH, mm, ss;
      let time = new Date(date);
      let timeDate;
      year = time.getFullYear(); // 年
      month = time.getMonth() + 1; // 月
      day = time.getDate(); // 日
      HH = time.getHours(); // 时
      mm = time.getMinutes(); // 分
      ss = time.getSeconds(); // 秒
  
      month = month < 10 ? '0' + month : month;
      day = day < 10 ? '0' + day : day;
      HH = HH < 10 ? '0' + HH : HH; // 时
      mm = mm < 10 ? '0' + mm : mm; // 分
      ss = ss < 10 ? '0' + ss : ss; // 秒
  
      switch (type) {
    
    
        case 'yyyy':
          timeDate = String(year);
          break;
        case 'yyyy-MM':
          timeDate = year + '-' + month;
          break;
        case 'yyyy-MM-dd':
          timeDate = year + '-' + month + '-' + day;
          break;
        case 'yyyy/MM/dd':
          timeDate = year + '/' + month + '/' + day;
          break;
        case 'yyyy-MM-dd HH:mm:ss':
          timeDate = year + '-' + month + '-' + day + '' + HH + ':' + mm + ':' + ss;
          break;
        case 'HH:mm:ss':
          timeDate = HH + ':' + mm + ':' + ss;
          break;
        case 'MM':
          timeDate = String(month);
          break;
        default:
          timeDate = year + '-' + month + '-' + day;
          break;
      }
      return timeDate;
    } else {
    
    
      return '';
    }
  };
  export default DateFormatPipe;
  

使用时我们就直接在组件(.vue文件中引用),然后在template里使用就好了

// 这里要写你自己的文件路径
// 注意我这里这样导入是因为我在文件导出时写了default,否则应该是import {} from ''
import DateFormatPipe from "../../utils/dateFormat.pipe";

template中使用

<a-table :loading="loading" rowKey="bizId" :data-source="loanCvmInfoList" :columns="columns" :pagination="false"
                :scroll="{ y: 240 }" :rowClassName="setRowClassName" :customRow="rowClick">
   <template #bodyCell="{ column, record, index }">
      <template v-if="column.key === 'amount'">
          <span>{
   
   { NumberFormatPipe(record.amount, 2) }}</span>
      </template>
      <template v-if="column.key === 'beginDate'">
          <span>{
   
   { DateFormatPipe(record.beginDate, 'yyyy-MM-dd') }}</span>
      </template>
      <template v-if="column.key === 'dueDate'">
           <span>{
   
   { DateFormatPipe(record.dueDate, 'yyyy-MM-dd') }}</span>
       </template>
   </template>
</a-table>

猜你喜欢

转载自blog.csdn.net/m0_56026872/article/details/125169483
今日推荐