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

Mur*_*lık 5 vue.js vuejs2

这是我组件的计算属性:

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();
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

和我的标记:

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();
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

我需要再次调用内部计算的过滤功能。激活收藏夹按钮。

mo3*_*o3n 45

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

这是代码:

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
  },
},

Run Code Online (Sandbox Code Playgroud)

  • 最好使用数字并递增它,而不是布尔值。在您的情况下,如果“myMethod”在同一个tick中被调用两次,则该值不会改变,并且计算值不会被重新评估。 (2认同)

mor*_*gul 3

无需强制更新计算值。如果所需值发生更改,计算属性将始终自动重新计算。

因此,就您的情况而言,您需要进行更改singlePlacesfilteredPlaces会自动更新。

关于数组和对象反应性,有一点需要注意,如文档中所示(https://v2.vuejs.org/v2/guide/reactivity.html#For-Arrays)所示。

在您的示例中,您在添加最喜欢的地点时没有包含代码,但您可能需要执行以下操作:

Vue.set(this.singlePlaces, indexOfItem, updatedItem)
Run Code Online (Sandbox Code Playgroud)