当前位置:首页 > VUE

vue实现点击选中列表

2026-02-25 06:52:28VUE

实现点击选中列表

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

基础实现(单选)

<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>

使用计算属性优化

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

vue实现点击选中列表

<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 实现文字播放栏(跑马灯效果) 方法一:使用 CSS 动画 + Vue 数据绑定 通过 CSS 的 @keyframes 实现动画效果,结合 Vue 的动态数据绑定控制内容。 <tem…

vue调用接口实现退出

vue调用接口实现退出

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

vue实现水印

vue实现水印

Vue 实现水印的方法 使用 CSS 背景图 通过 CSS 的 background-image 和 background-repeat 属性实现水印效果。创建一个包含水印文本的 Canvas,将其转…

vue实现数组

vue实现数组

Vue 实现数组操作的方法 在 Vue 中,数组的操作需要特别注意响应式的问题。Vue 提供了一些方法来确保数组的变动能够触发视图更新。 响应式数组方法 Vue 对以下数组方法进行了封装,确保它们能…

vue动画实现

vue动画实现

Vue动画实现方法 Vue提供了多种方式实现动画效果,主要通过内置组件和第三方库完成。 使用<transition>组件 Vue内置的<transition>组件可以为元素添…

vue mvvm 实现

vue mvvm 实现

Vue MVVM 实现原理 Vue.js 的 MVVM(Model-View-ViewModel)架构通过数据绑定和响应式系统实现视图与数据的自动同步。以下是其核心实现机制: 数据劫持与响应式系统…