当前位置:首页 > VUE

vue实现点击选中列表

2026-02-25 06:52:28VUE

vue实现点击选中列表

实现点击选中列表

在Vue中实现点击选中列表的功能,可以通过v-for指令渲染列表,结合v-bind:classv-model动态绑定选中状态。以下是两种常见实现方式:

vue实现点击选中列表

基础实现(单选)

<template>
  <ul>
    <li 
      v-for="(item, index) in list" 
      :key="index"
      @click="selectItem(index)"
      :class="{ 'active': selectedIndex === index }"
    >
      {{ item.name }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      list: [
        { name: 'Item 1' },
        { name: 'Item 2' },
        { name: 'Item 3' }
      ],
      selectedIndex: null
    }
  },
  methods: {
    selectItem(index) {
      this.selectedIndex = index
    }
  }
}
</script>

<style>
.active {
  background-color: #f0f0f0;
  color: #42b983;
}
</style>

多选实现

<template>
  <ul>
    <li 
      v-for="(item, index) in list" 
      :key="index"
      @click="toggleSelect(index)"
      :class="{ 'active': selectedItems.includes(index) }"
    >
      {{ item.name }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      list: [
        { name: 'Item 1' },
        { name: 'Item 2' },
        { name: 'Item 3' }
      ],
      selectedItems: []
    }
  },
  methods: {
    toggleSelect(index) {
      const idx = this.selectedItems.indexOf(index)
      if (idx > -1) {
        this.selectedItems.splice(idx, 1)
      } else {
        this.selectedItems.push(index)
      }
    }
  }
}
</script>

使用计算属性优化

对于复杂场景,可以使用计算属性管理选中状态:

<template>
  <ul>
    <li 
      v-for="(item, index) in list" 
      :key="item.id"
      @click="selectedId = item.id"
      :class="{ 'active': selectedId === item.id }"
    >
      {{ item.name }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      list: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' }
      ],
      selectedId: null
    }
  }
}
</script>

注意事项

  • 使用唯一标识(如id)作为key比数组索引更可靠
  • 选中状态可以存储在Vuex中实现跨组件共享
  • 对于大量数据,考虑使用虚拟滚动优化性能
  • 移动端可添加@touchstart事件提升响应速度

标签: 列表vue
分享给朋友:

相关文章

vue调用接口实现退出

vue调用接口实现退出

实现Vue退出功能的步骤 在Vue中调用接口实现退出功能通常需要与后端API交互,以下是实现方法: 前端实现 创建退出方法,调用后端API接口: methods: { logout() {…

vue实现跑车

vue实现跑车

Vue 实现跑车动画效果 使用 Vue 结合 CSS 动画可以实现跑车在屏幕上移动的效果。以下是一个完整的实现方案: 创建 Vue 组件结构 <template> <div c…

django vue实现

django vue实现

Django与Vue.js整合实现方案 Django作为后端框架与Vue.js作为前端框架的整合,可以通过以下方式实现: 分离式开发 前后端完全分离,Django仅提供API接口,Vue.js通过a…

通过vue实现

通过vue实现

Vue 实现方法 安装 Vue 确保已安装 Node.js 和 npm,通过以下命令安装 Vue CLI: npm install -g @vue/cli 创建 Vue 项目 使用 Vue CLI…

vue实现秒表

vue实现秒表

实现秒表功能 在Vue中实现秒表功能需要处理时间显示、开始、暂停和重置逻辑。以下是具体实现方式: 基础实现代码 <template> <div> <div&…

vue列表查询实现

vue列表查询实现

实现 Vue 列表查询功能 基础列表渲染 在 Vue 中可以通过 v-for 指令实现列表渲染,结合计算属性动态过滤数据: <template> <div> &l…