Vue v-for loop, add custom class
I am using v-for to scroll through a list and display that list.
Now, after rendering, each list has a title and hidden content, and I want to be able to when I select one title of that list, so that its content is displayed instead of all content.
So far, I do this (thanks @thanksd ):
<div class="link">
<p @click="show = true"> Click here to show the content </p>
<div v-show="show" class="content">
<p>This is the hidden content</p>
</div>
</div>
<div class="link">
<p @click="show = true"> Click here to show the content </p>
<div v-show="show" class="content">
<p>This is the hidden content</p>
</div>
</div>
data() {
return {
show: false,
};
}
source to share
You can write something like this:
<div class="link" v-for="(item, index) in items" :key="index">
<p @click="show = index"> Click here to show the content </p>
<div v-show="show === index" class="content">
<p>This is the hidden content</p>
</div>
</div>
If you are iterating over an object, the syntax is v-for="(value, key) in items"
. It is also recommended to now declare key
in loops.
Read the related document here .
source to share
There are many ways to do this, if you create a variable that will display the content, then it is easier
<div class="link" v-for="link in links">
<p @click="link.show = true"> Click here to show the content </p>
<div v-show="link.show" class="content">
<p>{{ link.content }}</p>
</div>
</div>
data() {
return {
links: [{
title: 'the title',
content: 'the hidden content',
show: false,
},{
title: 'the other title',
content: 'the other hidden content',
show: false,
},]
};
}
source to share
If you also want to hide it when the user clicks on it a second time, you need to add the triple comparison "show === index? Show = -1: show = index" to @ Leo's answer:
<div class="link" v-for="(item, index) in items" :key="index">
<p @click="show === index ? show = -1 : show = index"> Click here to show the content </p>
<div v-show="show === index" class="content">
<p>This is the hidden content</p>
</div>
</div>
data() {
return {
show: -1,
};
}
source to share