日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 Vue 正文

解決vue過濾器filters獲取不到this對象的問題_vue.js

作者:天堂の風 ? 更新時間: 2022-04-05 Vue

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>

原文鏈接:https://blog.csdn.net/ZZQ928000/article/details/105141690

欄目分類
最近更新