vue定义全局过滤器

时间:2021-09-01
本文章向大家介绍vue定义全局过滤器,主要包括vue定义全局过滤器使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、定义全局过滤器

1、src下新建文件夹utils,下面新建filter.js

import Vue from 'vue'

// 个人中心-支付状态
Vue.filter('paymentMethod', value => {
    switch (value) {
        case 1:
            return '微信支付'
        case 2:
            return '会员充值'
        case 3:
            return '钱包支付'
        default:
            return '其他'
    }
})

2、在main.js中引入使用

import '@/common/utils/filter.js';// 全局过滤器

3、使用

// 在双花括号插值
{{ value | paymentMethod }}

二、filter过滤器(多参数)传参

1、传1个参数

// html
{{a1 | filterAa}}
// js filters:{ filterAa(a1){ // a1是传入的参数 } }

2、传2个参数

// html
{{a1 | filterAa(a2)}}

// js
filters:{
  filterAa(a1,a2){
    // a1是传入的第一个参数
    // a2是传入的第二个参数
  }
}

3、传3个参数

// html
{{a1 | filterAa(a2,a3)}}

// js
filters:{
  filterAa(a1,a2,a3){
    // a1是传入的第一个参数
    // a2是传入的第二个参数
    // a3是传入的第三个参数
  }
}

三、过滤器在js中使用

this.$options.filters["thousand"](要处理的数据) 
this.$options.filters.formatDate(val);

注意:

1、 当有局部和全局两个名称相同的过滤器时候,会以就近原则进行调用,即:局部过滤器优先于全局过滤器被调用!

2、 一个表达式可以使用多个过滤器。过滤器之间需要用管道符“|”隔开。其执行顺序从左往右。

原文地址:https://www.cnblogs.com/zjianfei/p/15215085.html