vue 点击事件变色
时间: 2023-08-28 15:22:46 浏览: 211
要实现Vue中的点击事件变色效果,可以使用v-bind和v-on指令。首先,在data中定义一个变量来表示当前选中的元素的索引,例如currentIndex。然后,在对应的元素上绑定class属性,根据currentIndex的值来判断是否添加active类。最后,在点击事件的回调函数中,将currentIndex设置为当前点击元素的索引。
以下是示例代码:
```
<template>
<div>
<ul>
<li v-for="(item, index) in movies" :class="{ active: currentIndex === index }" @click="liClick(index)">
{{ index }}. {{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
movies: ['海王', '海贼王', '加勒比海盗', '海尔兄弟'],
currentIndex: 0
};
},
methods: {
liClick(index) {
this.currentIndex = index;
}
}
};
</script>
<style>
.active {
color: red;
}
</style>
```
在这个示例中,点击每个li元素会改变其颜色。点击其他元素时,之前变色的元素会恢复原来的颜色,始终只有一个元素是变色的。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [vue点击变色](https://blog.csdn.net/weixin_50501118/article/details/126475695)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [Vue实现点击后文字变色切换方法](https://download.csdn.net/download/weixin_38656226/12763530)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [vue实现点击某个标签元素,该标签元素显示红色](https://blog.csdn.net/qq_44316726/article/details/111186858)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文