I have 2 v-for loops:
<div v-for="(fret, index) in frets" :key="index">
<div >
<div >
<span
v-for="(string, index) in stringsNumber"
:key="index"
:string="string"
@click="showDot(fret, string)"
>
<div ></div>
</span>
</div>
<p v-if="fretNumberIsVisible">{{ index 1 }}</p>
</div>
<span ></span>
</div>
I have div with dot class on every string, but they are transparent and when I click on a single dot, I want to change background color on this element.
data() {
return {
frets: 10,
stringsNumber: 6,
fretNumberIsVisible: true,
dotIsVisible: false,
};
},
showDot(fret, string) {
this.dotIsVisible = !this.dotIsVisible;
console.log("fret number:" fret);
console.log("string number:" string);
},
It works, but It change background color of all elements.
CodePudding user response:
Try to set dotIsVisible
as object with fret and string instead of boolean, and if you want multiple selection save it in array:
const app = Vue.createApp({
data() {
return {
frets: 10,
stringsNumber: 6,
fretNumberIsVisible: true,
dotIsVisible: [],
};
},
methods: {
isSelected(fret, string) {
return this.dotIsVisible.find(d => (d.f === fret && d.s === string)) ? 'dot' : ''
},
showDot(fret, string) {
if (this.isSelected(fret, string)) {
this.dotIsVisible = this.dotIsVisible.filter(d => {
return (d.f !== fret || d.s !== string)
})
} else {
this.dotIsVisible = [...this.dotIsVisible, {f: fret, s: string}]
}
},
}
})
app.mount('#demo')
.dot {
background: red;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div v-for="(fret, index) in frets" :key="index">
<div >
<div >
<span
v-for="(string, index) in stringsNumber"
:key="index"
:string="string"
@click="showDot(fret, string)"
>
<div :>{{string}}</div>
</span>
</div>
{{dotIsVisible}}
<p v-if="fretNumberIsVisible">{{ index 1 }}</p>
</div>
<span ></span>
</div>
</div>