栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

vue实现的封装全局filter并统一管理操作示例

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

vue实现的封装全局filter并统一管理操作示例

本文实例讲述了vue实现的封装全局filter并统一管理操作。分享给大家供大家参考,具体如下:

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

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

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

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

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

index.js 代码如下:


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 + '日';
    }
  }
}

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]));

在页面中使用:

{{time | normalDate('/')}}

//这样时间戳就会转化为xxxx/xx/xx的格式

希望本文所述对大家vue.js程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/71545.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号