vue封装全局filter并统一管理

本文介绍在Vue项目中封装全局Filter的方法,特别是处理日期和时间的格式化,通过创建专用的filters目录,实现时间戳到指定格式的日期时间字符串转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在前后端分离的项目中,经常会有后台返回的数据需要进过处理才能显示到页面上的场景。

使用最多的场景就是日期和时间的处理,后台一般返回的都是时间戳,那么我们就要对时间戳进行处理。

下面就拿封装全局的处理日期和时间的 filter 来展示如何 vue 如何封装全局 filter 并统一处理。

src 目录下新建 filters 目录用来专门存放全局过滤器,如果项目的过滤器过多,那么就要按类型分类。

我司的项目需要前台处理的数据不是太多,那么就在 filters 目录下新建一个 index.js 来存放所有的过滤器就足够了。

index.js 代码如下:

  • /*
  • 日期处理
  • time:源时间戳
  • type:要处理的格式 默认 xxxx年xx月xx日
  • /: xxxx/xx/xx
  • .: xxxx.xx.xx
  • -: xxxx-xx-xx
  • */
  • export const normalDate = (time,type) => {
  • if (time) {
  • var date = new Date();
  • date.setTime(time);
  • var year = date.getFullYear();
  • var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) * 1 : date.getMonth() + 1;
  • var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  • if(type == '-'){
  • return year + '-' + month + '-' + day;
  • } else if(type == '/'){
  • return year + '/' + month + '/' + day;
  • } else if(type == '.'){
  • return year + '.' + month + '.' + day;
  • } else{
  • return year + '年' + month + '月' + day + '日';
  • }
  • }
  • }
  • /*
  • 时间处理
  • time:源时间戳
  • type:要处理的格式 默认 xxxx年xx月xx日 xx:xx:xx
  • /: xxxx/xx/xx xx:xx:xx
  • .: xxxx.xx.xx xx:xx:xx
  • -: xxxx-xx-xx xx:xx:xx
  • */
  • export const normalTime = (time,type) => {
  • if (time) {
  • var date = new Date();
  • date.setTime(time);
  • var year = date.getFullYear();
  • var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) * 1 : date.getMonth() + 1;
  • var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  • var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
  • var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  • var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  • if(type == '-'){
  • return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
  • } else if(type == '/'){
  • return year + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds;
  • } else if(type == '.'){
  • return year + '.' + month + '.' + day + ' ' + hours + ':' + minutes + ':' + seconds;
  • } else{
  • return year + '年' + month + '月' + day + '日' + ' ' + hours + ':' + minutes + ':' + seconds;
  • }
  • }
  • }
  • 然后在 main.js 中引入注册即可使用:

  • import * as filters from './filters'
  • Object.keys(filters).forEach( key => Vue.filter(key, filters[key]));
  • 在页面中使用:

    <p>{{time | normalDate(’/’)}}</p> //这样时间戳就会转化为xxxx/xx/xx的格式

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值