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,而在
created
、mounted
、methods
中, this
指向的都是当前 的Vue
实例
在filter的this指向的却是window
filters:{ choseWords(index){ console.log(this); } }解决方法1: 1.如果filter里面只需要一个参数,就把这个参数当做filter的第二个参数传进去使用,在模板中:
if="item.status == false">{{index|choseWords(word)}}{{item.askName}}
filters:{ choseWords(index,word){ return word[index]; } }解决方法2: 1. 如果filter里面只需要多个参数,就需要在data中定义一个变量存储this,例如:
data(){ return { that:this, ...... } }2. 在模板中直接传入这个that变量
if="item.status == false">{{index|choseWords(that)}}{{item.askName}}
filters:{ choseWords(index,that){ return that.word[index]; } }