首页 > 编程 > JavaScript > 正文

在Vue methods中调用filters里的过滤器实例

2019-11-19 13:06:22
字体:
来源:转载
供稿:网友

需求: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方法中可以使用过滤器中的方法。      })    },  },

我是这么解决的,大家如果还有更好的方法,希望大家写在评论里,欢迎大家批评指正。

以上这篇在Vue methods中调用filters里的过滤器实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表