列表渲染:
<ul v-for="item in arr">
这里开始渲染列表,arr是数据源,item是被迭代的数组元素的别名
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <div id="app"> <ul v-for="item in arr"> <li>{{item}}</li> </ul> </div> <script src="vue.js"></script> <script> const app = new Vue({ el: '#app', data: { arr: [12, 2, 5, 21, 421, 4] } }) </script> </body> </html>
v-for还支持第二个可选参数,既当前数组的索引
<ul v-for="(item,index)in arr">
下面是我们在课堂上做的一个案例:
(用到了bootstrap的样式,点这里跳转到bootstrap官网)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> [v-cloak] { display: none; } </style> </head> <body> <div id="app" :style="appsty" style="margin: 0 auto" v-cloak> <div v-if="books.length"> <h1 style="text-align: center">图书购物车</h1> <table class="table table-striped" style="border: 1px solid #eee"> <thead> <tr> <th></th> <th>书籍名称</th> <th>出版日期</th> <th>价格</th> <th>购买数量</th> <th>操作</th> </tr> </thead> <tbody> <template v-for="(item,index) in books"> <tr> <td>{{index}}</td> <td>{{item.name}}</td> <td>{{item.time}}</td> <td>¥{{item.price.toFixed(2)}}</td> <td> <button type="button" class="btn btn-default" @click="numberjian(index)" :disabled="item.number<=0"> - </button> {{item.number}} <button type="button" class="btn btn-default" @click.stop="numberjia(index)">
+
</button> </td> <td> <button type="button" class="btn btn-default" @click="del(index)">
移除
</button> </td> </tr> </template> </tbody> </table> 总价为:¥{{total.toFixed(2)}} </div> <div v-else style="color:green;text-align: center"> <h1>图书购物车</h1> <h1>暂无商品</h1> </div> </div> <script> var app = new Vue({ el: '#app', data: { appsty: "width:900px", result: 0, books: [ {name: "《遥远的救世主》", time: 2006, price: 45.00, number: 0}, {name: "《人类简史》", time: 2006, price: 45.00, number: 0}, {name: "《三体》", time: 2006, price: 45.00, number: 0} ] }, methods: { del(index) { this.books.splice(index, 1) }, numberjia(index) { this.books[index].number++; }, numberjian(index) { this.books[index].number--; if (this.books[index].number <= 0) { this.books[index].number = 0 } } }, computed: { total() { let result = 0; // for (let s in this.books) { // result += this.books[s].price * this.books[s].number; // } // for (let i = 0; i < this.books.length; i++) { // result += this.books[i].price * this.books[i].number; // } for (let i of this.books) { result += i.price * i.number } return result; } } }) </script> </body> <link rel="stylesheet" href="bootstrap.min.css">
<script src="vue.js"></script> </html>