Vue 列表渲染
封面图
•
2025-11-15
•
Vue
0
0
0
0
在 Vue 中,**列表渲染**是通过 `v-for` 指令实现的。它允许你遍历一个数组或对象,并为每个元素生成对应的 DOM 元素。 --- ## ✅ 1. 基本用法:遍历数组 ```html <template> <div> <ul> <li v-for="item in items" :key="item.id"> {{ item.name }} </li> </ul> </div> </template> <script> export default { data() { return { items: [ { id: 1, name: '苹果' }, { id: 2, name: '香蕉' }, { id: 3, name: '橘子' } ] }; } }; </script> ``` ### 注意: - 使用 `:key` 是为了帮助 Vue 识别每个节点的唯一性,提高渲染效率。 - `key` 应该是唯一的标识符(如 `id`),而不是索引(除非数据不会变化)。 --- ## ✅ 2. 遍历对象 ```html <template> <div> <ul> <li v-for="(value, key, index) in user" :key="key"> {{ key }}: {{ value }} </li> </ul> </div> </template> <script> export default { data() { return { user: { name: '张三', age: 25, gender: '男' } }; } }; </script> ``` 输出: - name: 张三 - age: 25 - gender: 男 --- ## ✅ 3. 使用索引 ```html <template> <div> <ul> <li v-for="(item, index) in items" :key="index"> {{ index + 1 }}. {{ item.name }} </li> </ul> </div> </template> ``` --- ## ✅ 4. 遍历数字(从 0 到 n) ```html <template> <div> <ul> <li v-for="n in 5" :key="n"> {{ n }} </li> </ul> </div> </template> ``` 输出:1, 2, 3, 4, 5 --- ## ✅ 5. 使用 `v-for` 和 `v-if` 的注意事项 - **不要在 `v-for` 中使用 `v-if`**,因为 `v-if` 会比 `v-for` 更高效地控制渲染。 - 如果需要条件渲染,可以使用计算属性过滤数据后再渲染。 ```html <template> <div> <ul> <li v-for="item in filteredItems" :key="item.id"> {{ item.name }} </li> </ul> </div> </template> <script> export default { data() { return { items: [ { id: 1, name: '苹果', available: true }, { id: 2, name: '香蕉', available: false }, { id: 3, name: '橘子', available: true } ] }; }, computed: { filteredItems() { return this.items.filter(item => item.available); } } }; </script> ``` --- ## ✅ 6. 使用 `v-for` 渲染组件(Vue 3 推荐) ```html <template> <div> <component-item v-for="item in items" :key="item.id" :item="item" /> </div> </template> ``` --- ## 📌 小贴士: | 指令 | 说明 | |------|------| | `v-for="item in items"` | 遍历数组 | | `v-for="(value, key) in obj"` | 遍历对象 | | `v-for="(value, key, index) in obj"` | 获取键、值和索引 | | `v-for="n in 5"` | 遍历数字 | | `:key` | 必须指定,用于优化渲染性能 | --- 如果你有具体场景(比如动态列表、分页、嵌套数据等),我可以提供更详细的示例。欢迎继续提问!
上一篇:
Vue内置组件Suspense
标题录入,一次不能超过6条
留言
评论