当前位置:首页 > VUE

vue列表实现

2026-01-07 08:36:16VUE

Vue 列表实现方法

使用 v-for 指令

v-for 是 Vue 中用于渲染列表的核心指令,基于数据源动态生成 DOM 元素。语法格式为 item in items(item, index) in items

<template>
  <ul>
    <li v-for="(item, index) in items" :key="item.id">
      {{ index }} - {{ item.name }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Apple' },
        { id: 2, name: 'Banana' }
      ]
    }
  }
}
</script>

绑定 key 属性

为每个列表项添加唯一的 key 属性,通常是数据中的唯一标识符(如 id)。这有助于 Vue 高效更新 DOM。

<li v-for="item in items" :key="item.id">
  {{ item.name }}
</li>

嵌套列表渲染

v-for 可嵌套使用,实现多维数据渲染。

vue列表实现

<template>
  <div v-for="category in categories" :key="category.id">
    <h3>{{ category.name }}</h3>
    <ul>
      <li v-for="product in category.products" :key="product.id">
        {{ product.name }}
      </li>
    </ul>
  </div>
</template>

条件渲染结合

通过 v-ifv-show 控制列表项的显示逻辑。

<li v-for="item in items" :key="item.id" v-if="item.isActive">
  {{ item.name }}
</li>

动态过滤与排序

使用计算属性对列表数据进行处理,实现过滤或排序功能。

vue列表实现

<template>
  <ul>
    <li v-for="item in filteredItems" :key="item.id">
      {{ item.name }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Apple', type: 'fruit' },
        { id: 2, name: 'Carrot', type: 'vegetable' }
      ],
      filterType: 'fruit'
    }
  },
  computed: {
    filteredItems() {
      return this.items.filter(item => item.type === this.filterType)
    }
  }
}
</script>

使用 template 标签包裹

当需要渲染多个兄弟元素且不希望引入额外 DOM 节点时,可使用 <template> 包裹。

<template v-for="item in items" :key="item.id">
  <p>{{ item.name }}</p>
  <button @click="select(item)">Select</button>
</template>

性能优化

对于长列表(如超过 1000 项),建议使用虚拟滚动库(如 vue-virtual-scroller)减少 DOM 节点数量。

<template>
  <RecycleScroller
    class="scroller"
    :items="items"
    :item-size="50"
    key-field="id"
  >
    <template v-slot="{ item }">
      <div class="item">
        {{ item.name }}
      </div>
    </template>
  </RecycleScroller>
</template>

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

相关文章

vue 实现手册

vue 实现手册

以下是关于 Vue.js 实现手册的整理内容,涵盖核心概念、实践方法和常见场景的解决方案: 核心概念与基础用法 Vue.js 是一个渐进式 JavaScript 框架,核心特点包括数据驱动视图和组…

vue循环数组实现

vue循环数组实现

vue循环数组的实现方法 在Vue中循环数组主要通过v-for指令实现,以下是几种常见用法: 基本数组循环 使用v-for指令遍历数组,可以通过(item, index)的语法获取当前项和索引值:…

vue实现自动翻译

vue实现自动翻译

Vue 实现自动翻译的方法 在 Vue 项目中实现自动翻译功能可以通过多种方式完成,以下是几种常见的方法: 使用第三方翻译 API 注册并获取翻译 API 的密钥(如 Google Transla…

vue实现tab换行

vue实现tab换行

Vue实现Tab切换的常见方法 使用Vue实现Tab切换功能可以通过多种方式完成,以下是几种常见的方法: 动态组件结合v-if或v-show 通过v-if或v-show控制不同Tab内容的显示与隐…

vue搜索过后实现分页

vue搜索过后实现分页

Vue 实现搜索后分页功能 数据绑定与搜索逻辑 在 Vue 组件中定义必要的数据属性: data() { return { searchQuery: '', currentPag…

vue实现文字播放栏

vue实现文字播放栏

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