gifteddiz
gifteddiz

Reputation: 15

Consecutive counting of visible elements on vue

I have a survey to fill out, some questions appear based on different conditions and I need to put numbers for them sequentially. So all these blocks are just in the template and can be hidden by v-if, and I need the numbering to take into account only the visible elements. Something like

<div class="el">
  <div class="el__qty">{{getNum()}}</div> // 1
  ...
</div>
<div class="el" v-if="someCondition">
  <div class="el__qty">{{getNum()}}</div> // 2 if visible
  ...
</div>
<div class="el">
  <div class="el__qty">{{getNum()}}</div> // 2 or 3
  ...
</div>

Upvotes: 0

Views: 570

Answers (2)

Rogier
Rogier

Reputation: 152

When having very similar repeating elements with such logic I would use e v-for and use the index as your counter, similar to:

Your template

<div v-for="(question, index) in questionListFiltered" :key="index">
  <span>{{index}}</span>
  <span>{{element.label}}</span>
</div>

Your initial questionlist (provided as a prop, or set in data, or retreived from your server etc.)

[
  {
    label: 'First label',
    show: true,
  },
  {
    label: 'Second label'
    show: false,
  },
  {
    label: 'Third label',
    show: true,
  },
]

A filtered list, which you can add at initialisation, or use a computed like:

questionListFiltered() => {
  return this.questionList.filter(question => question.show);
}

This would result in:

<div key="1">
  <span>1</span>
  <span>First label</span>
</div>
<div key="2">
  <span>2</span>
  <span>Third label</span>
</div>

Upvotes: 0

علی سالمی
علی سالمی

Reputation: 397

use css counter. css counter variable are reactive and handle by the browser. so when you hide one of them by display: none or remove by v-if other number updated automatically.

body {
  counter-reset: section;
}

h2::before {
  counter-increment: section;
  content: counter(section) ": ";
}
<h1>Using CSS Counters:</h1>
<h2>HTML Tutorial</h2>
<h2>CSS Tutorial</h2>
<h2>JavaScript Tutorial</h2>

Upvotes: 1

Related Questions