Vue中,methods中调用filters里的过滤器

需求:vue中,除了在模板中使用过滤器,有时候,methods中也需要使用filters中的过滤器,

网友hongz1125提出的解决办法:
this.$options.filters[filter](...args)   //这种方法很简单,也很实用

下面是我的方法,有点复杂。建议使用上面网友说的方法。

filters: {
        formatScore(score) {
            if (score < 20) {
                score = '不合格';
            } else if (score >= 20 && score <= 27) {
                score = '合格';
            } else if (score >= 28 && score <= 31) {
                score = '良好';
            } else if (score > 31) {
                score = '优秀';
            }
            return score
        }
    },
methods: {
    formatScore(score) {
        if (score < 20) {
            score = '不合格';
        } else if (score >= 20 && score <= 27) {
            score = '合格';
        } else if (score >= 28 && score <= 31) {
            score = '良好';
        } else if (score > 31) {
            score = '优秀';
        }
        return score
    },
    getPhysicalResult() {
        this.$http.get('/rc_ChildTest/testResult').then((res) => {
            this.isDisplayIcon = this.formatScore(score参数);//使用过滤器方法,需要单独写一个一模一样的方法。通过this调用
        })
    },
    },
解决方法:
1.建立一个公共的report.js文件,提取封装公共js
export default {
    formatScore(score) {
        if (score < 20) {
            score = '不合格';
        } else if (score >= 20 && score <= 27) {
            score = '合格';
        } else if (score >= 28 && score <= 31) {
            score = '良好';
        } else if (score > 31) {
            score = '优秀';
        }
        return score
    },
}
2.导入report.js 并使用
import report from 'js文件所在位置'
filters: {
        formatScore(score) {
            return report.formatScore(score);//使用导入的report.js中的report.formatScore方法
        }
    },
methods: {
        getPhysicalResult() {
            this.$http.get('/rc_ChildTest/testResult').then((res) => {
                this.isDisplayIcon = report.formatScore(score参数);//这里直接使用导入的report.js中的report.formatScore方法。在methods方法中可以使用过滤器中的方法。
            })
        },
    },
我是这么解决的,大家如果还有更好的方法,希望大家写在评论里,欢迎大家批评指正。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值