vue中使用filters的注意事项


1.报错:Failed to resolve filter: choseWords

在局部使用filter的时候,一定要注意语法,稍微一疏忽就会报这个错误

  filters:{
    changeMoney(money){
      return '¥' + money;
    }
  }
注意:这里一定是 filters,而不是 filter,有时候手误就写成 filter,结果导致报Failed to resolve filter的错误   全局filter定义如下:
Vue.filter('choseWords', function (money) {
     return '¥' + money;
  })
  2.filter中this指向的问题 在filter里面使用this是无法拿到data里面的数据的,显示变量都是undefined,而在 createdmountedmethods 中, this 指向的都是当前 的Vue 实例 在filter的this指向的却是window
 filters:{
    choseWords(index){
      console.log(this);
    }
  }
  解决方法1: 1.如果filter里面只需要一个参数,就把这个参数当做filter的第二个参数传进去使用,在模板中:
  • for="(item,index) in askList" :key="index">
    if="item.status == false">{{index|choseWords(word)}}{{item.askName}}
  •   2.filter过滤器如果不传值,会将管道前面的变量默认作为它第一个参数,如果传了参数,会作为第二个参数,在filters里面直接接收两个参数就可以了
      filters:{
        choseWords(index,word){
          return word[index];
        }
      }
      解决方法2: 1. 如果filter里面只需要多个参数,就需要在data中定义一个变量存储this,例如:
    data(){
        return {
          that:this,
      ......
      }
     }
    2. 在模板中直接传入这个that变量
  • for="(item,index) in askList" :key="index">
    if="item.status == false">{{index|choseWords(that)}}{{item.askName}}
  •   3. 在filters中就可以通过that变量获取任何data里面的数据
      filters:{
        choseWords(index,that){
          return that.word[index];
        }
      }