Reputation: 119
Is there a way I can insert new tag between every two v-for produced tags?
Like Array.join()
.
I want to insert a <span>,</span>
between every two <router-link></router-link>
.
<router-link></router-link>
is produced by v-for
, the code like this:
<router-link tag="a"
v-for="text in ['vue', 'react', 'JQuery']"
:key="text"
>
{{ text }}
</router-link>
Run it and seems like this:
vue react JQuery
I don't know how to directly insert <span>,</span>
between these so I move it into a <div>
:
<div v-for="text in ['vue', 'react', 'JQuery']"
:key="text">
<router-link tag="a">
{{ text }}
</router-link>
<span>, </span>
</div>
Run it and seems like this:
vue, react, JQuery,
so the question is that the last ‘,’ is redundant.
I can fix it by v-show
:
<div v-for="(text, index) in ['vue', 'react', 'JQuery']"
:key="text">
<router-link tag="a">
{{ text }}
</router-link>
<span v-show="index !== 2">, </span>
</div>
It works nice, but I want to know is there a easy way to do this?
Thanks response.
Upvotes: 2
Views: 116
Reputation: 128
As an addition to what jom said: I'd rather use v-if
than v-show
, because as the docs say:
prefer
v-show
if you need to toggle something very often, and preferv-if
if the condition is unlikely to change at runtime.
Since you do not want to toggle the comma at any point, just don't render it at all :)
Upvotes: 2
Reputation: 64164
Another addition to what has already been said. Inverting the order makes it easier to avoid the unneded comma (you always skip the first one, instead of need to take care of the array length)
<div v-for="(text, index) in ['vue', 'react', 'JQuery']"
:key="text">
<span v-if="index !== 0">, </span>
<router-link tag="a">
{{ text }}
</router-link>
</div>
Upvotes: 2
Reputation: 9180
Your last approach is the way to go, but you should probably use Array.length
for processing the last occurrence, in case the array changes.
<span v-show="index !== (items.length - 1)">, </span>
Or use plain CSS (notice I'm adding class route
on the div
element):
div.route:not(:last-child) > a::after {
content: ',';
text-decoration: none;
}
Upvotes: 4