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

2019-11-15,,,,,

需求: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里的过滤器实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • vue的过滤器filter实例详解
  • 在vue中使用公共过滤器filter的方法
  • vue自定义filters过滤器
  • vue 过滤器filter实例详解
  • web前端vue filter 过滤器
  • Vue 过滤器filters及基本用法
  • Vue filters过滤器的使用方法
  • vue计算属性computed、事件、监听器watch的使用讲解
  • vue-router传参用法详解
  • vue中过滤器filter的讲解

《在Vue methods中调用filters里的过滤器实例.doc》

下载本文的Word格式文档,以方便收藏与打印。