vue3中怎么处理时间格式

在 Vue 3 中处理时间格式,有几种方式:

1. 使用过去运算符 |
Vue 3 新增的过去运算符可以简单格式化时间。例如:

<p>{
   
   { 2021-10-10 | date }}</p>
<p>{
   
   { 2021-10-10 | time }}</p> 
<p>{
   
   { 2021-10-10 | datetime }}</p>

渲染:

10/10/2021 
10:00:00 
10/10/2021 10:00:00

2. 使用 DateTimeFormat
Vue 3 支持直接使用 Intl.DateTimeFormat 格式化时间。例如:

const df = new Intl.DateTimeFormat('en', { 
  year: 'numeric', 
  month: 'long', 
  day: 'numeric'
})

new Vue({
  template: '<p>{
   
   { date }}</p>',
  computed: {
    date() {
     return df.format(new Date(2021, 9, 10)) 
    }
  }  
}) 

这会渲染:

October 10, 2021

3. 使用第三方库
可以使用 date-fns 等第三方库格式化时间。例如:

import { format } from 'date-fns'

new Vue({
  template: '<p>{
   
   { date }}</p>',
  computed: {
    date() {
      return format(new Date(2021, 9, 10), 'MMM dd, yyyy')
    }
  }
})

这也会渲染:October 10, 2021所以,在 Vue 3 中主要的处理时间格式化的方式是:1. 使用内置的 | 过去运算符
2. 直接调用 Intl.DateTimeFormat
3. 使用第三方库如 date-fns与 Vue 2 相比,Vue 3 简化了时间格式化,内置支持更丰富的格式化功能,也更好的支持现代环境的 API 如 Intl。

猜你喜欢

转载自blog.csdn.net/qwe0415/article/details/130350246