4.5Vue的列表渲染
1.v-for的基本使用
v - for 的基本格式是 “item in 数组”:
- 数组通常是来自 data 或者 prop,也可以是其他方式;
- item 是我们给每项元素起的一个别名,这个别名可以自定义;
我们知道,在遍历一个数组的时候会经常需要拿到数组的索引:
- 如果我们需要索引,可以使用格式 “(item, index) in 数组”
- 注意上面的顺序:数组元素项 item 是在前面的,索引 index 在后面
html
预览
<template id="my - app"><h2>电影列表</h2><ul><li v - for="item in movies">{{item}}</li></ul> </template>
<html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head> <body><div id="app"><h2>{{message}}</h2><div class="box" v-for="item in produces"><h3>商品{{item.name}}</h3><span>{{item.price}}</span><p>秒杀:{{item.desc}}</p></div></div><script src="../lib/Vue.js"></script><script>const app = Vue.createApp({data:function(){return {message:"Hello Vue",produces:[{id:110,name:"手机",price:900,desc:10},{id:112,name:"电脑",price:700,desc:10},{id:118,name:"笔记本",price:500,desc:10}]}},})app.mount('#app')</script> </body> </html>