1. 程式人生 > 實用技巧 >vue的v-for遍歷以及案例

vue的v-for遍歷以及案例

列表渲染:

<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>&#65509;{{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> 總價為:&#65509;{{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>