You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中点击列表项时如何给选中元素添加active类(TypeScript环境)

解决方案

核心问题点

  • 你在setup中声明的isActive是普通非响应式变量,Vue无法监听它的数值变化,修改后视图不会同步更新
  • 所有循环生成的li共用同一个isActive状态,无法区分单个选中项,逻辑上就不可能实现单独项高亮
  • selectItem中的遍历逻辑完全错误,遍历过程中反复给isActive赋值,最终结果只会等于数组最后一项和选中项的匹配结果,没有实际作用

修正后完整代码

<template>
   <ul class="items">
        <li
          class="item"
          v-for="(item, index) in items"
          :key="index"
          @click="selectItem(index)"
          :class="{'active' : selectedIndex === index}"
        >
          {{ item }}
        </li>
      </ul>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue"
export default defineComponent({
  name: "Test",
  props: {
    id: Number,
    item: Object,
  },
  setup(props) {
    // 用ref创建响应式变量,存储当前选中项的索引,初始值-1代表无选中项
    const selectedIndex = ref(-1)
    const items = ["A", "B", "C", "D"]

    const selectItem = (index: number) => {
      // 直接赋值选中的索引即可
      selectedIndex.value = index
      // 如果需要支持点击取消选中,换成下面的逻辑
      // selectedIndex.value = selectedIndex.value === index ? -1 : index
    }

    return {
      items,
      selectItem,
      selectedIndex,
    }
  },
})
</script>

内容的提问来源于stack exchange,提问作者DnD2k21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:39:00