如何从为vuejs中列表中的单个元素动态创建的列表中删除类



点击是同时删除所有li的警报类,我想在点击后单独删除每个li的警报类别

模板

<ul>
<li v-for= "(post, index) in posts" 
:key="index" class=" lists alert" 
@click="removeAlert(index)">
{{ post.name }}
{{ post.content }}
</li>
</ul>

JS

removeAlert(index){
const items = this.$el.querySelectorAll('lists');

items.forEach((item, index)=>{
item.classList.remove('alert');
});
} 

您可以使用class-binding来完成此操作。

如您所见,我使用映射来存储li的哪个索引是警报。

  1. 单击时,它将调用toggleAlert来更新alertMap

  2. isAlert方法将返回值(true/false(,以便您确定是否需要添加alert类。

<template>
<ul>
<li v-for= "(post, index) in posts" 
:key="index" class="lists" 
@click="toggleAlert(index)"
:class="{ alert: !!isAlert(index) }"
>
{{ post.name }}
{{ post.content }}
</li>
</ul>
</template>
<script>
new Vue({
data: {
alertMap: {}
},
methods: {
toggleAlert: function(index) {
const key = index.toString()
if (alertMap[key]) alertMap[key] = true
else alertMap[key] = false
},
isAlert: function(index) {
const key = index.toString()
return alertMap[key]
}
}
})
</script>

顺便说一句,我的答案是用vue2写的,你可以把它改成vue3的作文。

最新更新