1

I have a construction like this:

<div v-for="item in items">
  <p>{{ f1(item).k1 }}</p>
  <p>{{ f1(item).k2 }}</p>
  <p>{{ f2(item).k3 }}</p>
  <p>{{ f2(item).k4 }}</p>
</div>

where f1 and f2 are the component's methods that return objects with the fields k1, k2, k3, k4. In this example the methods are called as many times as many keys I need in the template, that can be expensive.

Is there a way to store the results of calculations into variables v1 and v2 to prevent multiple calls?

I found a solution for one temporary variable:

<div v-for="item in items" :set="v1 = f1(item)">
  <p>{{ v1.k1 }}</p>
  <p>{{ v2.k2 }}</p>
</div>

but I couldn't generalize it for the case with two variables elegantly. Also I met the solutions to create a different component for the tag with v-for instead of div I used, it seems to be too complicated and bulky.

3
  • Are you saying both f1 and f2 return objects with k1 through k4 properties? Commented Jun 13, 2019 at 6:53
  • It does not matter. What matters is f1 and f2 are two completely different functions that I do not want to merge into one. Commented Jun 13, 2019 at 6:57
  • Do the objects returned have overlapping keys or not? I ask as it might make the answer a little neater Commented Jun 13, 2019 at 6:59

1 Answer 1

2

It's almost universally a bad idea to call methods from your template.

This is really what computed properties are for.

computed: {
  calculatedItems () {
    return this.items.map(item => ({
      f1: this.f1(item),
      f2: this.f2(item)
    }))
  }
}

This will only execute when required (ie, if items changes). Now you can iterate this in your template without making any method calls

<div v-for="item in calculatedItems">
  <p>{{ item.f1.k1 }}</p>
  <p>{{ item.f1.k2 }}</p>
  <p>{{ item.f2.k3 }}</p>
  <p>{{ item.f3.k4 }}</p>
</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.