需求: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里的過濾器實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答