i'm quite new to vue and can't figure out how to do it, i have several buttons and i need to select only one when clicked, i did it via
:class="isActive ? 'on' : 'off'"
v-on:click ="isActive = !isActive"
but this activates all the buttons, then I understand that I need to somehow distinguish the target button from the non-target one, but I can’t figure out how to do this. I can't find suitable implementation examples can you provide code examples
data() {
return {
isActive: true,
color: ‘’,
};
},
<template>
<div id="btn-box">
<button
type="button"
class="btn off"
@click="component='BorderLeftComonent', toggleShowPopup()">
<div
style="padding: 0 5px; width: 25px; margin: 0 auto; font-size: 25px;"
:style="{ 'border-left': `4px solid ${color}` }">A</div>
</button>
<button
type="button"
class="btn off"
@click="component='TextBalloonComponent'">
<div
class="bubble"
style="margin: 0 auto; width: 25px; font-size: 25px;">A</div>
</button>
<button
type="button"
class="btn off"
@click="component='DashedComponent'">
<div
style="border: 4px dashed #f5d018; margin: 0 auto; width: 45px; font-size: 25px;">A</div>
</button>
</div>
</template>
Use v-for directive to iterate over an array of button objects where each object includes it's own isActive property that can be toggled by the onclick event.
<button
v-for="(button, index) in buttons"
:key="index"
:class="button.isActive ? 'on' : 'off'"
@click="button.isActive = !button.isActive"
>
<div :class="`btn btn-${button.type}`">{{ button.label }}</div>
</button>
data() {
return {
buttons: [
{
label: "A",
isActive: false,
type: "border-left",
},
{
label: "A",
isActive: false,
type: "text-balloon",
},
{
label: "A",
isActive: false,
type: "dashed",
},
],
};
}
<style scoped>
.btn {
padding: 0 5px;
width: 25px;
margin: 0 auto;
font-size: 25px;
}
.btn-border-left {
border-left: 4px solid #f55;
}
.btn-dashed {
border: 4px dashed #f5d018;
width: 45px;
}
</style>
It seems that you need a button group, a classic component in UI libraries. Have a look at this one for example.
For example below, you have 4 buttons next to each other, and each button is highlighted when you click on it, see gif below.
And in your code, you have access to a property (here "text") that reflects which button is selected. Code taken from the link above:
<v-btn-toggle
v-model="text"
tile
color="deep-purple accent-3"
group
>
<v-btn value="left">
Left
</v-btn>
<v-btn value="center">
Center
</v-btn>
<v-btn value="right">
Right
</v-btn>
<v-btn value="justify">
Justify
</v-btn>
</v-btn-toggle>
Does that answer your question?