仅在 v-for 中显示关联数据
I have the following code:
<template>
<div>
<div v-for="title in titles">
<h1>{{ title }}</h1>
<a @click="showSub">Click Here</a>
<div v-if="subshown">
Shown
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
subshown: false,
titles: []
}
},
methods: {
showSub: function () {
this.subshown = true;
// do something more
}
}
}
</script>
When i now click on the Click Here
Button, the associated subshown
from the current title should be shown. At the moment, when i click on Click Here
, all subshown
are shown.
How to implement that only the associated is shown?
解决方案Add a property called currentIndex
then update it using the click event and use it in conditional rendering :
<template>
<div>
<div v-for="(title,index) in titles">
<h1>{{ title }}</h1>
<a @click="showSub(index)">Click Here</a>
<div v-if="currentIndex===index">
Shown
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex:-1,
titles: []
}
},
methods: {
showSub: function (index) {
this.currentIndex=this.currentIndex===index?-1:index
// do something more
}
}
}
</script>
相关文章