Resolving values to a name for reuse in a template (like with)

I have some template code which looks something like this:

<div v-for="n in appStore.yearsToCompute" :key="n">
  <span>{{ n + appStore.startingYear - 1 }}: {{ yearMap.get(n + appStore.startingYear - 1).name }}, {{ yearMap.get(n + appStore.startingYear - 1).salary }}</span>

I am using properties of properties and indexes of properties and it is a lot of repeat code. I am wondering if Vue has some kind of “with” statement so I can resolve the value once, making my template code look much cleaner and smaller, i.e.:

<div v-for="n in appStore.yearsToCompute" :key="n">
  <WITH year="n + appStore.startingYear - 1" data="yearMap.get(year)">
    <span>{{ year }}: {{ }}, {{ data.salary }}</span>


The “with” statement you want is essentially a computed property.

Do all your computations within it and return the result to be rendered. Not only will your template be much cleaner/more legible, but the value of the computed will be cached and therefore the logic more efficient.

A computed property won’t work, because the expression is dependent on the value in the current iteration in the loop. Instead, there is a special trick/hack you can use:

<li v-for="id in users" :key="id" :set="user = getUser(id)">
  <img :src="user.avatar" />
  {{ }}
  {{ user.homepage }}
1 Like

You do the loop within the computed, essentially pre-caching your values to be rendered by the template thus shifting the logic out of the template.