1. 程式人生 > 實用技巧 >vue中使用filters的注意事項

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: 如果filter裡面只需要一個引數,就把這個引數當做filter的第二個引數傳進去使用,在模板中: <liv-for="(item,index)inaskList":key="index"> <divv-if="item.status==false">{{index|choseWords(word)}}{{item.askName}}</div>
</li> filter過濾器如果不傳值,會將管道前面的變數預設作為它第一個引數,如果傳了引數,會作為第二個引數,在filters裡面直接接收兩個引數就可以了 filters:{ choseWords(index,word){ returnword[index]; } } 解決方法2: 如果filter裡面只需要多個引數,就需要在data中定義一個變數儲存this,例如: data(){ return{ that:this,   ......   }  } 在模板中直接傳入這個that變數 <liv-for="(item,index)inaskList":key="index">
<divv-if="item.status==false">{{index|choseWords(that)}}{{item.askName}}</div> </li> 在filters中就可以通過that變數獲取任何data裡面的資料 filters:{ choseWords(index,that){ return that.word[index]; } }