Vue.js 缓存方法结果?

Vue.js cache method outcome?

我目前有一个循环,它在该循环中调用同一个函数两次,如下所示:

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

因为 count 方法被调用了两次,所以更难调试 count 函数,因为在 console.log 之类的东西上,所有值都会出现两次。

第一个计数方法只是检查它是否为零,而另一个表示计数。有没有一种简单的方法可以重新使用 count 方法的结果,这样我实际上不必调用它两次。已经有结果了就不用再调用了

诸如计算 属性 之类的东西将无法工作,因为我需要传递当前迭代密钥。

遗憾的是,设计方法总是会重新渲染,没有可用的缓存 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.

来源:https://vuejs.org/v2/guide/computed.html

顺便说一句,我认为大多数时候仍然可以使用计算 属性:

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)
            });
        })
    }
}

然后遍历计算的道具:

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

    <span class="items">{{ value.count }}</span>
</div>