Here is my component's computed property:
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();
});
}
}
And my markup:
<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>
I need to call the filtering function inside computed again. To activate the Favorite button.
You can call a method from computed properties or watchers.
The Basics of Vue Reactivity Simply put, a computed property's dependencies are the reactive values that help the property that determine the value that is returned. If none of these change, then, again, the cached value will be returned. If no reactive dependency is changed, a computed property is not recalculated.
So this is a long way of saying that computed properties can only do synchronous work: they must return a value immediately. If you try to do something async, then you'll end up returning a Promise instead of the real value. Nope, if you need to do something asynchronous, then you can't use a computed property.
There is no need to force a computed value to update. A computed property will always be recomputed automatically if a needed value is changed.
So, in your case, you will need to change singlePlaces
and filteredPlaces
will automatically be updated.
There is a thing to note about Array and Object reactivity as seen in the doc (https://vuejs.org/v2/guide/reactivity.html#For-Arrays).
In your example, you did not include the code when adding a favorite place, but you will probably need to do something like this:
Vue.set(this.singlePlaces, indexOfItem, updatedItem)
If you want to force a computed property to update and recalculate it's value, you can simply use a data property and just mention that property in the computed function (you don't have to use it, just being there is enough), and then change that data property; This will force the computed value to update.
Here is the code:
data() {
return {
refreshKey: false,
// ...
}
},
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 = !this.refreshKey;
// the rest of my method
},
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With