vue项目——简单实现全局注册过滤器+好用的过滤器函数

新建filter.js文件,里面定义需要的过滤器函数,格式如下

/**
 * 格式化日期
 * @param {string} time 时间戳
 * @param {string} type 分隔符 需要手动传入
 * 使用方法 {
    
    {1946777545617 | formatDate('/')}}
 */
export const formatDate = (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 + type + month + type + day;
    } else {
    
    
      return year + "年" + month + "月" + day + "日";
    }
  }
};

在main.js文件内使用全局过滤器注册方法,项目中数据后跟 | 管道符使用即可

//全局过滤器注册
import * as filters from './config/filters/filters'

Object.keys(filters).forEach(key => {
    
    
  Vue.filter(key,filters[key])
})

import * as xxx from ""将引入的所有数据添加到xxx对象中
Object.keys 将对象中的key值取出添加到数组中

猜你喜欢

转载自blog.csdn.net/weixin_51198863/article/details/113251559