Skip to content

Variable assignment in loops in templateΒ #7201

Open
@grandsong

Description

@grandsong

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions