SoFunction
Updated on 2025-04-04

vue uses v-for loop to get the last item in the array

Use v-for loop to get the last item in the array

<span v-for="(item,i) in list" >
      <i style="display: none" v-if="i!=0">/</i>
      <i >{{item}}</i>
      <br/>
 </span>

Suppose we don't know the size of the list and want to use/segment, but the last one is not needed. We can use the above method

<span v-for="(item,i) in list" >
      <i >{{item}}</i>
      <i style="display: none" v-if="i!=-1">/</i>
      <br/>
 </span>

Suppose we know the size of the list and want to use/segment, but the last one is not needed. We can use the above method

vue v-for determines whether it is the last one

In Vue, you can use the $index and $last attributes to determine whether the element in v-for is the last one.

For example:

&lt;ul&gt;
  &lt;li v-for="(item, index) in items" :key="index"&gt;
    {{  }}
    &lt;span v-if="index !==  - 1"&gt;|&lt;/span&gt; &lt;!-- Determine whether it is the last one --&gt;
  &lt;/li&gt;
&lt;/ul&gt;

In the above code, v-if determines whether the index of the current element is equal to the index of the last element of the items array - 1. If it is not the last element, the | separator is displayed.

In addition, you can also use the $last attribute to determine whether it is the last element

For example:

&lt;ul&gt;
  &lt;li v-for="(item, index) in items" :key="index"&gt;
    {{  }}
    &lt;span v-if="!$last"&gt;|&lt;/span&gt; &lt;!-- Determine whether it is the last one --&gt;
  &lt;/li&gt;
&lt;/ul&gt;

In the above code, v-if determines whether the current element is the last element in v-for, and if it is not the last element, the | separator is displayed.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.