在Vue JS的v-for循环中点击按钮仅给当前对应元素添加类的问题
问题原因
你当前的实现中所有循环生成的元素共用了同一个全局响应式变量appear,修改该变量后所有绑定了它的div都会同步更新样式,因此点击任意按钮都会触发所有div变更类名。
解决方案
这里提供两种常用实现方案,可根据业务场景选择:
方案1:每个todo项独立控制状态(支持多个div同时激活)
这种方案给每个todo项单独添加激活状态标识,互不影响,适合需要同时展开多个块的场景。
修改后完整代码如下:
<template> <div v-for="(todo, index) in todos" :key="index" class="relative"> <button @click="showDiv(todo)"> show div </button> <div :class="todo.isActive ? 'left-2/4' : 'left-0'" class="absolute bg-red-500"> <p>{{ todo.text }}</p> </div> </div> </template> <script> import {defineComponent} from 'vue' export default defineComponent({ data() { return { todos: [ { text: 'Learn Laravel', isActive: false }, { text: 'Learn Vue JS', isActive: false }, { text: 'Learn Tailwind CSS', isActive: false }, ] } }, methods: { showDiv(todo) { // 如果需要点击切换显隐,可改为 todo.isActive = !todo.isActive todo.isActive = true } } }) </script>
方案2:绑定激活索引(同一时间仅一个div激活)
这种方案只存当前激活的项索引,适合同一时间只需要展开一个块的场景。
修改后完整代码如下:
<template> <div v-for="(todo, index) in todos" :key="index" class="relative"> <button @click="activeIndex = index"> show div </button> <div :class="index === activeIndex ? 'left-2/4' : 'left-0'" class="absolute bg-red-500"> <p>{{ todo.text }}</p> </div> </div> </template> <script> import {defineComponent} from 'vue' export default defineComponent({ data() { return { activeIndex: -1, // 默认全部不激活 todos: [ { text: 'Learn Laravel' }, { text: 'Learn Vue JS' }, { text: 'Learn Tailwind CSS' }, ] } } }) </script>
内容的提问来源于stack exchange,提问作者Jake
相关产品推荐
相关产品推荐

