点击是同时删除所有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
的哪个索引是警报。
-
单击时,它将调用
toggleAlert
来更新alertMap
-
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的作文。