vuejs / vuejs/core

Variable assignment in loops in template

Open
#7,201 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

:sparkles: feature request
Dominant language
TypeScript
Stars
54.4k
Forks
9.2k
Avg merge
1d 5h
Merged PRs (30d)
140

Description

What problem does this feature solve?

Sometimes, we need to compute a variable for each iteration of a loop and use this varible for multiple times.
An example:

.SimpleGrid
  .row(v-for="(v, row_idx) in row_count_")
    .cell(v-for="(v, column_idx) in column_count")
      slot(v-if="items[row_idx * column_count + column_idx]" :item="items[row_idx * column_count + column_idx]")

Here, items[row_idx * column_count + column_idx] is repeated.

Note: the total cells may be more than the length of items, so v-if="items[...]" is needed.

So far, I've discovered only one hack, thanks to How to define variable in vue template?:

.SimpleGrid
  .row(v-for="(v, row_idx) in row_count_")
    .cell(v-for="(v, column_idx) in column_count")
      template(v-for="item in [ items[row_idx * column_count + column_idx] ]")
        slot(v-if="item" :item="item")

It works. But we still need a formal way instead of such hack.

What does the proposed API look like?

In most (if not all) cases, variables follow loop iterations. (Otherwise, we should use computed for the whole component.)

I suggest a new directive v-let besides v-for:

.SimpleGrid
  .row(v-for="(v, row_idx) in row_count_")
    .cell(v-for="(v, column_idx) in column_count" v-let="item = items[row_idx * column_count + column_idx]")
      slot(v-if="item" :item="item")

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No implementation file, test, or entry point is named. Start by locating the template directive handling and existing v-for behavior, then determine how a formal v-let directive should fit the proposed loop-scoped assignment; done means the example works without the array-based workaround and has coverage for the new behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
frontend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.