当前位置:首页 > VUE

vue实现列表循环

2026-03-28 09:03:33VUE

使用 v-for 指令实现列表循环

Vue 的 v-for 指令是渲染列表的核心方法,可以遍历数组或对象。基本语法如下:

<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' },
        { id: 3, name: 'Orange' }
      ]
    };
  }
};
</script>

绑定 key 的重要性

为每个循环项添加唯一的 key 属性(通常使用 id)能帮助 Vue 高效更新 DOM。避免使用索引 index 作为 key,除非列表是静态的。

<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 userInfo" :key="key">
      {{ key }}: {{ value }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {
        name: 'John',
        age: 30,
        role: 'Developer'
      }
    };
  }
};
</script>

性能优化:避免 v-ifv-for 共用

在同一元素上同时使用 v-ifv-for 会导致性能问题。推荐通过计算属性过滤数据:

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

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Apple', active: true },
        { id: 2, name: 'Banana', active: false },
        { id: 3, name: 'Orange', active: true }
      ]
    };
  },
  computed: {
    activeItems() {
      return this.items.filter(item => item.active);
    }
  }
};
</script>

动态更新列表

直接通过数组方法(如 pushsplice)修改数据,Vue 会自动触发视图更新:

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

使用 <template> 包裹多元素

需要循环渲染多个兄弟元素时,用 <template> 包裹并添加 v-for

vue实现列表循环

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

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

相关文章

vue实现付款

vue实现付款

Vue 实现付款功能 在 Vue 中实现付款功能通常需要集成第三方支付网关(如支付宝、微信支付、Stripe 等)。以下是常见的实现方法: 集成支付宝/微信支付 安装必要的依赖(如 axios 用于…

vue实现翻译

vue实现翻译

Vue 实现翻译功能的方法 使用 i18n 插件实现多语言切换 安装 vue-i18n 插件: npm install vue-i18n 创建语言资源文件(如 en.json 和 zh.json):…

vue实现筛选

vue实现筛选

实现筛选功能的基本思路 在Vue中实现筛选功能通常需要结合数据绑定、计算属性和方法。筛选的核心逻辑是根据用户输入的条件过滤原始数据列表,并动态更新显示结果。 数据准备 定义一个数组存储原始数据,另一…

vue nexttick 实现

vue nexttick 实现

Vue nextTick 实现原理 Vue 的 nextTick 是一个用于在下次 DOM 更新循环结束之后执行延迟回调的方法。它主要用于确保在 DOM 更新完成后执行某些操作。 核心实现机制 ne…

vue实现兼容

vue实现兼容

Vue 兼容性实现方案 Vue.js 的兼容性主要涉及对不同浏览器、Vue 版本以及第三方库的支持。以下是常见的兼容性解决方案: 浏览器兼容性 使用 Babel 转换 ES6+ 代码为 ES5 语…

vue实现饼图

vue实现饼图

使用 ECharts 实现 Vue 饼图 安装 ECharts 依赖 npm install echarts --save 在 Vue 组件中引入 ECharts import * as echa…