I'm trying to make every single element created with the v-for the ability to toggle between 'face' class, but it happens that it toggles everything created with the v-for.
<div >
<div v-for="base in cards" :key="base.id" >
<div : @click="face = !face">
<img style="z-index: 3" alt="Vue logo" :src="require('../assets/rightCardSide.png')">
</div>
<div : @click="face = !face">
<img style="z-index: 2" :src="require(`../assets/images/${base.url}`)">
</div>
</div>
</div>
```
export default {
setup() {
const face = ref(false)
return { face }
},
data(){
return {
face: false,
}
},
methods: {
}
}
CodePudding user response:
Create a component to encapsulate the v-for
content.
// new-component.vue
<template>
<div>
<div : @click="face = !face">
<img style="z-index: 3" alt="Vue logo" :src="require('../assets/rightCardSide.png')">
</div>
<div : @click="face = !face">
<img style="z-index: 2" :src="require(`../assets/images/${base.url}`)">
</div>
</div>
</template>
export default {
data(){
return {
face: false
}
}
}
Now update v-for
to use the new component.
<div >
<div v-for="base in cards" >
<new-component :key="base.id"/>
</div>
</div>
CodePudding user response:
You can use base.id
instead boolean and v-show
directive:
const { ref } = Vue
const app = Vue.createApp({
el: "#demo",
setup() {
const face = ref(false)
const cards = ref([{id: 1, url: "https://picsum.photos/100"}, {id: 2, url: "https://picsum.photos/101"}, {id: 3, url: "https://picsum.photos/102"}])
const rightCardSide = ref("https://picsum.photos/103")
const setFace = (val) => {
face.value = val
}
return { cards, face, rightCardSide, setFace }
},
})
app.mount('#demo')
.deckPairs {
display: flex;
}
.deckBoxOne {
cursor: pointer;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div >
<div v-for="base in cards" :key="base.id" >
<div v-show=" face !== base.id" @click="setFace(base.id)">
<img alt="Vue logo" :src="rightCardSide">
</div>
<div v-show="face === base.id" @click="setFace(false)">
<img :src="base.url">
</div>
</div>
</div>
</div>