当前位置:首页 > VUE

vue列表怎么实现

2026-03-08 20:15:32VUE

实现 Vue 列表的基础方法

使用 v-for 指令可以动态渲染列表。将 v-for 绑定到数组上,遍历数组中的每个元素并生成对应的 DOM 节点。

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

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

使用 :key 提高性能

v-for 中必须为每个节点绑定唯一的 key,Vue 依赖 key 进行高效的 DOM 更新。通常使用唯一标识符(如 id)而非数组索引。

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

遍历对象

v-for 也可以遍历对象的属性,语法为 (value, key, index)

<template>
  <ul>
    <li v-for="(value, key) in user" :key="key">
      {{ key }}: {{ value }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      user: {
        name: 'John',
        age: 30,
        email: 'john@example.com'
      }
    }
  }
}
</script>

结合计算属性动态过滤列表

通过计算属性可以动态过滤或排序列表数据,避免直接修改原始数据。

<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', category: 'fruit' },
        { id: 2, name: 'Carrot', category: 'vegetable' },
        { id: 3, name: 'Banana', category: 'fruit' }
      ],
      filterCategory: 'fruit'
    }
  },
  computed: {
    filteredItems() {
      return this.items.filter(item => item.category === this.filterCategory)
    }
  }
}
</script>

使用 v-for 结合 v-if 的条件渲染

Vue 3 允许 v-forv-if 同时作用在同一个元素上,但建议优先使用计算属性过滤数据以提高性能。

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

列表动态更新

Vue 会响应数据变化自动更新 DOM。直接修改数组(如 pushsplice)或替换整个数组均可触发视图更新。

methods: {
  addItem() {
    this.items.push({ id: 4, name: 'New Item' })
  },
  removeItem(index) {
    this.items.splice(index, 1)
  }
}

使用 <template> 渲染多元素块

如果需要渲染多个元素但不希望包裹额外 DOM,可以使用 <template> 标签。

vue列表怎么实现

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

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

相关文章

vue设计与实现 书

vue设计与实现 书

vue设计与实现 书 《Vue.js设计与实现》是一本深入探讨Vue.js框架内部原理和设计思想的书籍,适合希望深入理解Vue.js的开发者。以下是关于这本书的详细信息: 书籍内容 《Vue.js设…

vue实现波形

vue实现波形

实现波形效果的方法 在Vue中实现波形效果可以通过多种方式完成,常见的方法包括使用Canvas绘制、CSS动画或第三方库。以下是几种实现方案: 使用Canvas绘制波形 通过Canvas API动态…

vue实现抽屉

vue实现抽屉

Vue 实现抽屉组件 抽屉组件是一种常见的 UI 模式,通常用于从屏幕边缘滑出内容。以下是几种实现抽屉的方法: 使用 Vue 原生实现 创建一个基本的抽屉组件,利用 Vue 的过渡和条件渲染功能。…

vue导航实现

vue导航实现

Vue 导航实现方法 在 Vue 中实现导航功能通常涉及路由配置、组件设计和状态管理。以下是几种常见的实现方式: 使用 Vue Router 实现基础导航 安装 Vue Router: npm i…

vue实现反转

vue实现反转

实现数组反转 在Vue中反转数组可以通过多种方式实现,以下是几种常见方法: 使用JavaScript原生reverse方法 // 在methods中定义方法 methods: { revers…

vue实现点击提交

vue实现点击提交

Vue 实现点击提交功能 在 Vue 中实现点击提交功能通常涉及表单处理和事件绑定。以下是几种常见的实现方式: 使用 v-on 或 @ 绑定点击事件 通过 v-on:click 或简写 @click…