解決vue過濾器filters獲取不到this對象的問題
更新時間:2022年01月23日 11:26:30 作者:天堂の風
這篇文章主要介紹了解決vue過濾器filters獲取不到this對象的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
vue過濾器filters獲取不到this對象
原理
- 在data中定義一個屬性that,把this存儲到that中
- 在調用filters中的方法sum的時候將that傳進去即可
下面舉個例子
用filters計算data中 a+b 的值
- 注意:filters中的sum方法的第一個參數是|左邊那個a,第二個參數才是括號寫的that
<template>
? <div>{{a|sum(that)}}</div>
</template>
<script>
? export default {
? ? name: "test",
? ? data() {
? ? ? return {
? ? ? ? that: this,
? ? ? ? a: 1,
? ? ? ? b: 2
? ? ? }
? ? },
? ? filters: {
? ? ? sum(a, that) {
? ? ? ? console.log(that);
? ? ? ? return a + that.b;
? ? ? }
? ? },
? }
</script>Vue filters this指向問題
Vue實例中filter不依賴于當前vue實例上下文
所以在filter中無法直接訪問當前vue實例, 所以可以使用computed替代。
可是當遇到需要根據html文本改變,v-for的數據等情況而改變時,computed的功能就無法滿足我們的需求了。
那我們就可以使用methods代替
data: {
? ? shopItemType: {}
},
methods: {?
?? ?shopItemType2str(id){
? ? ? ? return this.shopItemType[id];
? ? }
}<tr v-for="shopItem in shopItems">
?? ?<td>{{shopItemType2str(shopItem.item_type)}}</td>
</tr>以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

