Vue3.2+TS在v-for的时候,循环处理时间,将其变成xx-xx-xx xx:xx:xx格式,最后教给大家自己封装一个时间hooks,直接复用

文章介绍了如何在Vue3.2项目中使用TypeScript进行时间格式转换,并演示了如何通过创建时间处理hooks实现代码复用。作者给出了未封装和封装后的代码片段,以及创建utils文件夹存放公共函数的方法。
摘要由CSDN通过智能技术生成
Vue3.2+TS在v-for的时候,循环处理时间,将其变成xx-xx-xx xx:xx:xx格式
最后教给大家自己封装一个时间hooks,直接复用
1.没有封装,直接使用
<template>
  <div>
    <ul>
      <li v-for="item,index in arr" :key="item">
      {{index}}-----{{item}}---{{formateDate(item)}}
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
const arr:string[] = [
  'Wed Aug 10 2023 16:51:08 GMT+0800 (中国标准时间)',
  'Wed Aug 12 2022 16:53:03 GMT+0800 (中国标准时间)',
  'Wed Aug 11 2021 16:54:04 GMT+0800 (中国标准时间)',
  'Wed Aug 05 2020 16:55:03 GMT+0800 (中国标准时间)',
  'Wed Aug 09 2019 16:56:01 GMT+0800 (中国标准时间)',
]
const formateDate = (date:string)=> {
  if (!date)  return '';
  const timer = new Date(date)
  let year = timer.getFullYear()
  let mouth = addZero(timer.getMonth() + 1)
  let day = addZero(timer.getDate())
  let hour = addZero(timer.getHours())
  let min = addZero(timer.getMinutes())
  let sec = addZero(timer.getSeconds())
  return `${year}-${mouth}-${day} ${hour}:${min}:${sec}`  
}

const addZero = (num:number)=>{
  return num > 9 ? num : `0${num}`
}

</script>
<style scoped lang="less">
ul{
  list-style-type: none;
  li{
    height: 30px;
    line-height: 30px;
    background-color: aqua;
    margin-bottom: 10px;
  }
}

</style>
假如我们现在其他地方还需要用到这个,那么我们可以把这个方法封装成一个hooks,用以复用
1.在src目录下,新建一个utils文件夹,定义一个timehandle文件,将需要的时间格式转化函数放进去,然后导出。
export const formateDate = (date:string)=> {
  if (!date)  return '';
  const timer = new Date(date)
  let year = timer.getFullYear()
  let mouth = addZero(timer.getMonth() + 1)
  let day = addZero(timer.getDate())
  let hour = addZero(timer.getHours())
  let min = addZero(timer.getMinutes())
  let sec = addZero(timer.getSeconds())
  return `${year}-${mouth}-${day} ${hour}:${min}:${sec}`  
}

const addZero = (num:number)=>{
  return num > 9 ? num : `0${num}`
}
2.在需要用到这个函数的组件内,将其导入
<template>
  <div>
    <ul>
      <li v-for="item,index in arr" :key="item">
      {{index}}-----{{item}}---{{formateDate(item)}}
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import {formateDate} from './utils/timehandle'
const arr:string[] = [
  'Wed Aug 10 2023 16:51:08 GMT+0800 (中国标准时间)',
  'Wed Aug 12 2022 16:53:03 GMT+0800 (中国标准时间)',
  'Wed Aug 11 2021 16:54:04 GMT+0800 (中国标准时间)',
  'Wed Aug 05 2020 16:55:03 GMT+0800 (中国标准时间)',
  'Wed Aug 09 2019 16:56:01 GMT+0800 (中国标准时间)',
]


</script>
<style scoped lang="less">
ul{
  list-style-type: none;
  li{
    height: 30px;
    line-height: 30px;
    background-color: aqua;
    margin-bottom: 10px;
  }
}

</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值