Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js cache method outcome?

I currently have a loop which calls the same function twice in that loop like so:

<div class="checkbox" v-for="(value, key) in range">
    <input type="checkbox" :disabled="count(Number(key)) === 0">

    <span class="items">{{ count(Number(key)) }}</span>
</div>

Because the count method is being called twice it makes it harder to debug the count function because on something like a console.log all values will appear twice.

The first count method simply checks if it is zero while the other represents the count. Is there a simple way to re-use the outcome of the count method so I don't actually have to call it twice. There is no need to call it again when I already have the outcome.

Something like a computed property won't work because I need to pass the current iteration key.

like image 876
Stephan-v Avatar asked Jun 13 '17 08:06

Stephan-v


1 Answers

Sadly by design a method will always re-render, there is no cache availible afaik:

In comparison, a method invocation will always run the function whenever a re-render happens.

Why do we need caching? Imagine we have an expensive computed property A, which requires looping through a huge Array and doing a lot of computations. Then we may have other computed properties that in turn depend on A. Without caching, we would be executing A’s getter many more times than necessary! In cases where you do not want caching, use a method instead.

Source: https://v2.vuejs.org/v2/guide/computed.html

By the way I think it's still possible to use a computed property most of the time:

computed: {
    rangeWithCount() {
        // assuming that range is an array, otherwise use Object.entries()
        return this.range.map((value, key) => {
            // assuming value is already an object, otherwise create a new one
            return Object.assign({}, value, {
                count: foo(key)
            });
        })
    }
}

And just iter over the computed prop:

<div class="checkbox" v-for="value in rangeWithCount">
    <input type="checkbox" :disabled="value.count === 0">

    <span class="items">{{ value.count }}</span>
</div>
like image 144
FitzFish Avatar answered Sep 22 '22 18:09

FitzFish