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