So let's say I have a list.
<div>
<ul>
<li>Item1</li>
<li>Item2</li>
<li>Item3</li>
</ul>
</div>
I only want every item after Item1 to be visible once a user clicks a button. I could do this easily by creating a boolean called showItem, set it to false and then create a click event that sets it to true in a method.
<div @click="showItemBtn">
<ul>
<li>Item1</li>
<li v-if="showItem">Item2</li>
<li v-if="showItem">Item3</li>
</ul>
</div>
method: {
showItemBtn() {
this.showItem = true
}
}
But is there a more clean way of doing this, so I don't have to add a v-if statement to every single item that comes after Item1?
CodePudding user response:
I'd add a v-for
logic to the items
with a reactive bool value with adding the click logic in the template. Here You don't need to have the click methoh in the Vue logic.
new Vue({
el: "#app",
data: {
showItem: false,
// You can add your list items here
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div @click="showItem = true">
<ul>
<li>Item1</li>
<li v-for="index in 3" v-if="showItem">Item{{ index 1 }}</li>
</ul>
</div>
</div>
CodePudding user response:
You can use v-for for your items:
new Vue({
el: "#demo",
data() {
return {
items: ['Item1', 'Item2', 'Item3'],
showItem: false
}
},
methods: {
showItemBtn() {
this.showItem = true
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div @click="showItemBtn">
<ul>
<li>Item</li>
<div v-for="item in items">
<li v-if="showItem">{{ item }}</li>
</div>
</ul>
</div>
</div>
CodePudding user response:
Wrap the elements into the <template>
element and use the v-if
directive to the <template>
only once.
new Vue({
el: "#app",
data() {
return {
showItem: false,
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div @click="showItem = !showItem">
<ul>
<li>Item1</li>
<template v-if="showItem">
<li>Item2</li>
<li>Item3</li>
</template>
</ul>
</div>
</div>
If looping is possible you can try the below way as well. I used the key as a unique id for demonstration, you can use anything which is unique.
new Vue({
el: "#demo",
data() {
return {
items: ['Item1', 'Item2', 'Item3'],
showItem: false
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div @click="showItem = !showItem">
<ul>
<template v-for="(item,index) in items">
<!-- If first item show direct otherwise check condition -->
<li :key="index" v-if="index == 0 || showItem">
{{ item }}
</li>
</template>
</ul>
</div>
</div>