Vue.js 强制计算属性重新计算?

新手上路,请多包涵

这是我的组件的计算属性:

 methods: {
  addFavoritePlace(place_id) {
    axios.post('/api/add-favorite-place', { place_id: place_id })
      .then(response => {
        // I need here force command.
      });
  },
},

computed: {
  filteredPlaces: function () {
    var is_open;

    if (this.showOpened) {
      is_open = 'open'
    } else {
      is_open = 'close'
    }

    return this.singlePlaces.filter((j) => {
        return j.name.toLowerCase().match(this.search.toLowerCase();
    });
  }
}

我的标记:

 <span @click="addFavoritePlace(place.id)" class="favorite-btn active" v-if="place.is_favorited == true">
  <i class="icon-heart"></i>
</span>

<span @click="addFavoritePlace(place.id)" class="favorite-btn" v-else>
  <i class="icon-heart"></i>
</span>

我需要再次调用computed里面的过滤函数。激活收藏夹按钮。

原文由 Murat Sağlık 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
1 个回答

如果你想 强制计算属性更新 并重新计算它的值,你可以简单地 _使用数据属性并在计算函数中提及该属性_(你不必使用它,只要存在就足够了),然后更改该数据属性;这将强制更新计算值。

这是代码:

 data() {
  return {
    refreshKey: 0,
    // ...
  }
},
computed: {
  myComputedValue() {
    // just mentioning refreshKey
    this.refreshKey;

    // rest of the function that actualy do the calculations and returns a value
  },
},
methods: {
  myMethod() {
    // the next line would force myComputedValue to update
    this.refreshKey++;

    // the rest of my method
  },
},

原文由 mo3n 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题