gpt4 book ai didi

javascript - VueJs - 循环中的动态类

转载 作者:行者123 更新时间:2023-11-28 03:20:07 25 4
gpt4 key购买 nike

每次我选择一个 div 元素时,我只希望该元素改变颜色。使用我当前的代码,当我单击一个元素时,它会使用变量 color 更改所有项目的颜色,但我不知道如何仅使选定的元素更改颜色。

这是我的代码:

 <div class="row">        
<div v-for="(item, index) in seatShows" :key="index">
<div class="col-auto" @click="select(item)">
<div class="icon icon-shape text-white" :class="[color]">
<img src="/images/butaca2-lg.png" class="position-relative">
<a class="text-white position-absolute"> {{item.id_seat}} </a>
</div>
</div>
</div>
</div>

这是我的 Vue 代码:

export default {
props: ['route'],
data() {
return {
seatShows: this.route,
color: 'bg-seat-empty',
}
},
methods:{
select(item) {
this.color = 'bg-primary';
console.log(item) ;
return this.color;
},
sel(item) {
console.log(item.status_ticket);
}
}
}

最佳答案

好吧,您将 color 类分配给循环中的所有元素。因此,当您更新它时,所有元素都将具有该颜色。

如果您希望每个元素具有不同的颜色,那么您只需为每个元素添加 color 属性并使用以下方法更改它:

<div v-for="(item, index) in seatShows" :key="index">
<div class="col-auto" @click="select(item)" >
<div class="icon icon-shape text-white" :class="[item.color]">
...
</div>
</div>
</div>

seatShows: [
{id: 0, title: 'item1', color: 'bg-seat-empty'},
{id: 1, title: 'item2', color: 'bg-seat-empty'},
{id: 2, title: 'item3', color: 'bg-seat-empty'}
]

...

methods: {
getSeatShows() {
// Get seatShows data
// ...

// Add property "color" to seatShows data
this.seatShows.forEach(element => {
if (element.status === 0) {
element['color'] = 'bg-seat-empty'
}
else if (element.status === 1) {
element['color'] = 'bg-seat-full'
}
})
},
select(item) {
// Method 1
this.seatShows[item.id].color = item.color

// Method 2 (can be used to find items by some other unique property)
// let itemIndex = this.seatShows.findIndex(element => element.id === item.id)
// this.seatShows[itemIndex].color = item.color
}
}

关于javascript - VueJs - 循环中的动态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59238048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com