当前位置: 首页 > ops >正文

Vue3 学习教程,从入门到精通,Vue3 循环语句(`v-for`)语法知识点与案例详解(13)

Vue3 循环语句(v-for)语法知识点与案例详解

在 Vue3 中,v-for 指令用于基于一个数组或对象渲染一个列表。它是构建动态内容(如列表、表格等)的核心工具。以下将详细介绍 v-for 的语法、用法以及相关知识点,并通过一个详细的案例代码进行说明。


一、v-for 语法

1. 遍历数组

基本语法:

<div v-for="(item, index) in items" :key="index">{{ item }}
</div>
  • item:当前遍历的元素。
  • index:当前元素的索引(可选)。
  • items:要遍历的数组。
  • :key:每个元素唯一的标识符,推荐使用唯一且稳定的值(如 ID),避免使用索引作为 key,除非列表是静态的或不需要动画。

2. 遍历对象

基本语法:

<div v-for="(value, key, index) in object" :key="key">{{ key }}: {{ value }} (索引: {{ index }})
</div>
  • value:当前属性的值。
  • key:当前属性的键。
  • index:当前属性的索引(从 0 开始)。
  • object:要遍历的对象。

3. 遍历数字

基本语法:

<div v-for="n in 10" :key="n">{{ n }}
</div>
  • n:从 1 到指定数字(此处为 10)的数字。
  • :key:推荐使用数字本身作为 key

4. 使用 of 代替 in

Vue 也支持使用 of 关键字,语义上更接近于“迭代”:

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

二、v-for 的注意事项

  1. 使用唯一的 key:为每个循环项提供一个唯一的 key,有助于 Vue 高效地更新和重用 DOM 元素。避免使用数组索引作为 key,除非列表是静态的或不需要重新排序。

  2. 避免直接修改数组或对象:Vue 不能检测到某些数组变动(如直接通过索引修改数组元素或直接添加新属性到对象)。应使用 Vue 提供的变异方法(如 pushsplice)或 Vue.set 方法来修改数据。

  3. 嵌套使用 v-for:可以在一个组件内嵌套使用多个 v-for,但要确保每个 v-for 都有独立的 key

  4. 性能优化:对于大型列表,考虑使用虚拟滚动或分页来优化性能。


三、案例代码详解

以下是一个使用 Vue3 的完整示例,展示如何使用 v-for 渲染一个用户列表和用户详情。代码中包含详细注释,便于理解。

<template><div><h1>用户列表</h1><!-- 搜索功能 --><input v-model="searchQuery" placeholder="搜索用户" /><!-- 用户列表 --><ul><li v-for="(user, index) in filteredUsers" :key="user.id"><span>{{ index + 1 }}. {{ user.name }}</span><button @click="toggleDetails(user.id)">查看详情</button><!-- 用户详情 --><div v-if="detailsVisibility[user.id]" class="user-details"><p><strong>邮箱:</strong> {{ user.email }}</p><p><strong>电话:</strong> {{ user.phone }}</p><p><strong>地址:</strong> {{ user.address.street }}, {{ user.address.city }}, {{ user.address.zipcode }}</p></div></li></ul></div>
</template><script>
import { ref, computed } from 'vue';export default {name: 'UserList',setup() {// 用户数据数组const users = ref([{id: 1,name: '张三',email: 'zhangsan@example.com',phone: '1234567890',address: {street: '北京市朝阳区',city: '北京',zipcode: '100000'}},{id: 2,name: '李四',email: 'lisi@example.com',phone: '0987654321',address: {street: '上海市浦东新区',city: '上海',zipcode: '200000'}},// 可以添加更多用户]);// 搜索查询const searchQuery = ref('');// 计算过滤后的用户列表const filteredUsers = computed(() => {return users.value.filter(user => user.name.includes(searchQuery.value) ||user.email.includes(searchQuery.value));});// 控制用户详情的可见性const detailsVisibility = ref({});// 切换用户详情的显示const toggleDetails = (id) => {// 使用 Vue 的响应式方法更新对象属性detailsVisibility.value = {...detailsVisibility.value,[id]: !detailsVisibility.value[id]};};return {users,searchQuery,filteredUsers,detailsVisibility,toggleDetails};}
};
</script><style scoped>
.user-details {margin-left: 20px;padding: 10px;border-left: 2px solid #42b983;
}
input {margin-bottom: 20px;padding: 8px;width: 300px;
}
button {margin-left: 10px;padding: 5px 10px;background-color: #42b983;color: white;border: none;border-radius: 3px;cursor: pointer;
}
button:hover {background-color: #369c6b;
}
</style>

代码详解

  1. 模板部分 (<template>)

    • 搜索功能

      <input v-model="searchQuery" placeholder="搜索用户" />
      

      使用 v-model 实现双向绑定,用户输入的搜索内容会实时更新 searchQuery

    • 用户列表渲染

      <ul><li v-for="(user, index) in filteredUsers" :key="user.id">...</li>
      </ul>
      

      使用 v-for 遍历 filteredUsers(过滤后的用户列表),每个 li 元素都有唯一的 key(用户的 id)。

    • 用户详情显示

      <div v-if="detailsVisibility[user.id]" class="user-details">...
      </div>
      

      detailsVisibility 对象中对应用户的 idtrue 时,显示用户详情。

    • 按钮点击事件

      <button @click="toggleDetails(user.id)">查看详情</button>
      

      点击按钮时,调用 toggleDetails 方法,切换对应用户的详情显示状态。

  2. 脚本部分 (<script>)

    • 导入 Vue 3 组合式 API

      import { ref, computed } from 'vue';
      
    • 定义响应式数据

      const users = ref([...]);
      const searchQuery = ref('');
      const detailsVisibility = ref({});
      

      使用 ref 定义用户数据、搜索查询和详情可见性。

    • 计算过滤后的用户列表

      const filteredUsers = computed(() => {return users.value.filter(user => user.name.includes(searchQuery.value) ||user.email.includes(searchQuery.value));
      });
      

      使用 computed 计算属性,根据 searchQuery 过滤用户列表。

    • 切换用户详情显示状态

      const toggleDetails = (id) => {detailsVisibility.value = {...detailsVisibility.value,[id]: !detailsVisibility.value[id]};
      };
      

      通过展开运算符和计算属性更新 detailsVisibility 对象,实现切换单个用户的详情显示。

  3. 样式部分 (<style scoped>)

    • 样式定义

      .user-details {margin-left: 20px;padding: 10px;border-left: 2px solid #42b983;
      }
      input {margin-bottom: 20px;padding: 8px;width: 300px;
      }
      button {margin-left: 10px;padding: 5px 10px;background-color: #42b983;color: white;border: none;border-radius: 3px;cursor: pointer;
      }
      button:hover {background-color: #369c6b;
      }
      

      定义用户详情、输入框和按钮的样式。


四、运行效果

  1. 用户列表显示:用户列表会根据 searchQuery 的内容实时过滤显示。用户姓名字段或邮箱字段包含搜索关键词的用户会被显示。

  2. 查看详情:点击“查看详情”按钮,可以显示或隐藏对应用户的详细信息。

  3. 响应式更新:所有更新都是响应式的,Vue 会自动重新渲染必要的部分,无需手动操作 DOM。


五、总结

通过上述内容,我们详细介绍了 Vue3 中 v-for 指令的语法、注意事项,并通过一个完整的案例代码展示了如何在实际项目中应用 v-for 渲染动态列表。这个案例不仅涵盖了基本的循环渲染,还包括了搜索功能、动态显示详情以及样式定义等内容,适合 Vue3 初学者学习和参考。

http://www.xdnf.cn/news/15957.html

相关文章:

  • 渗透第2次作业
  • 学习游戏制作记录(战斗系统简述以及击中效果)7.22
  • Mixed Content错误:“mixed block“ 问题
  • Kotlin 中的单例模式(Singleton)与对象声明
  • SpringBoot+Mybatis+MySQL+Vue+ElementUI前后端分离版:权限管理(三)
  • Android开发:Java与Kotlin深度对比
  • 用ffmpeg 进行视频的拼接
  • ni-app 对鸿蒙的支持现状
  • Redis的五大基本数据类型
  • 有关Spring的总结
  • 【每日算法】专题十七_多源 BFS
  • React基础(1)
  • 【HarmonyOS】ArkUI - 声明式开发范式
  • 空间曲线正交投影及其距离计算的理论与实践
  • Anaconda 路径精简后暴露 python 及工具到环境变量的配置记录 [二]
  • 苍穹外卖Day5
  • JAVA+AI教程-第三天
  • 使用Python绘制专业柱状图:Matplotlib完全指南
  • 原型与原型链
  • 三大工厂设计模式
  • 2025杭电多校赛(2)1006 半
  • I2S音频的时钟
  • Zabbix 企业级分布式监控系统深度解析
  • Leetcode力扣解题记录--第238题(前/后缀积)
  • Windows防火墙配置详解
  • 暑期算法训练.5
  • Xilinx FPGA XCKU115‑2FLVA1517I AMD KintexUltraScale
  • day058-docker常见面试题与初识zabbix
  • 果园里的温柔之手:Deepoc具身智能如何重塑采摘机器人的“生命感知”
  • CS课程项目设计4:支持AI人机对战的五子棋游戏