0π
TLDR; Ideally your
card
should be a separate component as such each component would maintain its own local state.
Having said that in your above example, you can do the following:
- Do not mix jQuery with Vue code. You wonβt need it.
- Think in terms of MVVM and not DOM manipulations.
Your code would be:
<div id="card-1">
<ul v-if="!isHidden(1)">
<li>hello</li>
<li>world</li>
</ul>
<a @click="toggle(1)">
<span id="list-toggler-btn-1">
<template v-if="isHidden(1)">
<i class="fa fa-chevron-down"></i> Show all units
</template>
<template v-else>
<i class="fa fa-chevron-up"></i> Hide all units
</template>
</span>
</a>
</div>
<div id="card-2">
<ul v-if="!isHidden(2)">
<li>banana</li>
<li>apple</li>
<li>mango</li>
</ul>
<a @click="toggle(2)">
<span id="list-toggler-btn-2">
<template v-if="isHidden(2)">
<i class="fa fa-chevron-down"></i> Show all units
</template>
<template v-else>
<i class="fa fa-chevron-up"></i> Hide all units
</template>
</span>
</a>
</div>
The JavaScript side code should be:
new Vue({
el: '#app',
data() {
return {
// Maintain a list of hidden cards
// Initially empty
hiddenCards: []
}
},
methods:{
toggle(cardNumber) {
// Assuming each card has unique cardNumber
let hiddenCard = this.hiddenCards.find(cardNumber);
if (hiddenCard) {
// Item is hidden. Remove from hidden list and show it.
this.hiddenCards = this.hiddenCards.filter((x) => x !== cardNumber);
} else {
// Hide the card now by adding to the list.
this.hiddenCards = this.hiddenCards.concat(cardNumber);
}
},
isHidden (cardNumber) {
return this.hiddenCards.findIndex(cardNumber) > -1;
}
}
});
Source:stackexchange.com