vue项目中时间格式化

724 阅读1分钟

时间格式的修饰方法 之一

  1. 安装格式化时间的第三方包 dayjs

      npm i dayjs\@1.10.7 -S
    
  2. 在项目入口文件 main.js 中导入并使用 dayjs,定义全局过滤器:

         import dayjs from 'dayjs'
    

    // 定义全局过滤器 vue的过滤器方法(在vue3中过滤被淘汰了 )

         Vue.filter('dateFormat', (dt) => {
      return dayjs(dt).format('YYYY-MM-DD HH:mm:ss')
         })
    
  3. ArtList.vue 组件中,调用全局过滤器,对时间进行格式化:

        <el-table-column label="发表时间">
       <template #default="{ row }">
          {{ row.pub_date | dateFormat }}
     </template>
    </el-table-column>
    

时间格式的修饰方法 之二

  1. 安装格式化时间的第三方包 dayjs

     npm i dayjs\@1.10.7 -S
    
  2. 在需要的第地方(组件中) 导入并使用

  3. import dayjs from 'dayjs'
    

3 在methods:{}中定义函数 定义函数 formatDate()

// 定义格式化时间函数

 formatDate(time){
//dayjs().format()
return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

4 在需要的组件中使用 时间函数 (利用作用域插槽的写法 )

 <el-table-column label="发表时间">
  <template #default="{ row }">
      {{formatDate(row\.pub\_date) }} 
  </template> </el-table-column>