Using v-for in VueJS

Chào mọi người này mình có một demo nhỏ xây dụng bằng VueJS, mình muốn chia sẻ với mọi người về cách chúng ta sử dụng v-for trong vuejs để lặp các mảng đối tượng json, mình không chú trọng gì nhiều chỉ giới thiệu cho mọi người biết và sử dụng thôi

Video hướng dẫn


Ví dụ mình có một mảng đối tượng json trong file data.json mình lưu vào một file import bắt cứ nơi nào mình muốn dùng nó cho thuận lợi nhé

[
                {
                        "id":123,
                        "name":"Cafe",
                        "categories":[
                            {
                                "_id":1,
                                "price":35000,
                                "name":"Cafe rang xay",
                                "info":"Cà phê HERO 100 % nguyên chất, được lựa chọn kỹ, không hóa chất, không chất độn, không chất bảo quản. Nay đã có gói tiện lợi chỉ 10,000/gói. Thật tiện dụng và dễ dàng để thưởng thức cà phê, mặc cho cuộc sống hối hả.",
                                "rating":3,
                                "check":true,
                                 "favorites":[
                                     {
                                         "like":10,
                                         "unlike":2
                                     }
                                 ]
                            },
                            {
                                "_id":2,
                                "price":45000,
                                "name":"Cafe bột HERO",
                                "info":"Cà phê 100 % được lựa chọn kỹ, không hóa chất, không chất độn, không chất bảo quản. Giá chỉ 69,000 cho túi 250gr.",
                                "rating":4,
                                "check":true,
                                "favorites":[
                                     {
                                         "like":10,
                                         "unlike":2
                                     }
                                 ]
                            },
                            {
                                "_id":3,
                                "price":50000,
                                "name":"Cafe sữa HERO",
                                "info": "Cà phê sữa HERO thơm ngon do được chọn lọc kỹ càng từ những nguyên liệu tuyệt phẩm.",
                                "rating":3,
                                "check":true,
                                "favorites":[
                                     {
                                         "like":10,
                                         "unlike":2
                                     }
                                 ]
                            }
                        ]
                    }
                ]

Ở bên trên mình dùng đối tượng mảng json, các bạn cũng thấy mình có khai báo như (like,unlike, rating) mình dùng để xử lý sự kiện khi click vào nó tăng giá trị lên theo ý muốn của mình

Giờ các bạn tạo một project vue-cli để có thể sử dụng vuejs hoặc bạn có thể import đường link CDN Vuejs vào sử dụng cũng được nhé! ở trong bài này mình tạo project bằng VUE-CLI, các bạn có thể xem lại bài này để tìm hiểu thêm nhé: READ DATA FROM FILE USING FILEREADER API IN VUEJS

Ở đây mình tạo một file tên là ForJson.vue mình tạo giao diện template cho file này như sau:

<template>
    <div class="row">
            <div class="col-md-2"></div>
        <div class="col-md-8">
            <h2>List products</h2>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>categories</th>
                    </tr>
                </thead>
                <tbody>
                        <tr v-for="(product, index) in products">
                                <td>{{product.id}}</td>
                                <td>{{product.name}}</td>
                                <td>
                                    <div>
                                        <div v-for="(item,key) in product.categories" class="box-show">
                                            <p><strong>Name:</strong>{{item.name}}</p><br/>
                                            <p><strong>price:</strong>{{item.price}}</p><br/>
                                            <p><strong>infomation:</strong>{{item.info}}</p><br/>
                                            <p><span class="label label-primary" v-on:click="checkLike(index,key)" disabl>Like:{{item.favorites[0].like}}</span> </p>
                                            <p><span class="label label-warning" v-on:click="checkUnLike(index,key)">UnLike:{{item.favorites[0].unlike}}</span> </p>
                                            <p><strong>rating:</strong>{{item.rating}}</p><br/>
                                            <p v-if="item.check"><strong>Check rating:</strong><span v-on:click="checkRating(index,key)" class="label label-danger">Check</span></p><br/>
                                          
                                        </div>
                                        
                                    </div>
                                </td>
                        </tr>
                </tbody>
            </table>
        </div>
        <div class="col-md-2"></div>
    </div>
</template>

Trong đoạn mã bên trên mình dùng v-for để lập các thông tin trong mảng đối tượng products của mình ra template ,các bạn nhìn lại dữ liệu file json của mình bên trên, các bạn thấy trong products có một mảng đối tượng json là categories nửa vậy để chúng ta có thể for các đối tượng bên trong ra bên ngoài nửa thì ta cũng cần một v-for tiếp tục để trỏ tới đới tượng categories và lặp nó ra

Bên cạnh đó mình có tạo 3 sự kiện của là khi mình bấm like(checkLike)  và unlike(checkUnLike), rating(checkRating), các bạn xem đoạn code xử lý 3 sự kiện này của mình như sau:

 import Products from './data.json';
    export default{
        data(){
            return{

                products:Products
            }
        },
        methods:{
            checkRating:function(index,key){
                this.products[index].categories[key].rating++;
                this.products[index].categories[key].check=false;
            },
            checkLike:function(index,key){
                this.products[index].categories[key].favorites[0].like++;
            },
            checkUnLike:function(index,key){
                this.products[index].categories[key].favorites[0].unlike++;
            }
        }
    }

Để có thể lấy được vị trí của từng đối tượng trong mảng và cập nhật nó bạn cần chèn cho nó một cái vị trí hiện tại khi for mảng đối tượng, các bạn có thể thấy v-for của mình bên trên dùng là v-for="(product,index) in products) index là nó đưa ra vị trí của đối tượng, bạn có thể dựa vào index này để cập nhật đối tượng mảng json

Dưới đây là full code của file ForJson.vue của mình như sau:

<template>
    <div class="row">
            <div class="col-md-2"></div>
        <div class="col-md-8">
            <h2>List products</h2>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>categories</th>
                    </tr>
                </thead>
                <tbody>
                        <tr v-for="(product, index) in products">
                                <td>{{product.id}}</td>
                                <td>{{product.name}}</td>
                                <td>
                                    <div>
                                        <div v-for="(item,key) in product.categories" class="box-show">
                                            <p><strong>Name:</strong>{{item.name}}</p><br/>
                                            <p><strong>price:</strong>{{item.price}}</p><br/>
                                            <p><strong>infomation:</strong>{{item.info}}</p><br/>
                                            <p><span class="label label-primary" v-on:click="checkLike(index,key)" disabl>Like:{{item.favorites[0].like}}</span> </p>
                                            <p><span class="label label-warning" v-on:click="checkUnLike(index,key)">UnLike:{{item.favorites[0].unlike}}</span> </p>
                                            <p><strong>rating:</strong>{{item.rating}}</p><br/>
                                            <p v-if="item.check"><strong>Check rating:</strong><span v-on:click="checkRating(index,key)" class="label label-danger">Check</span></p><br/>
                                          
                                        </div>
                                        
                                    </div>
                                </td>
                        </tr>
                </tbody>
            </table>
        </div>
        <div class="col-md-2"></div>
    </div>
</template>
<style>
    table tr td p{float: left;text-align: left;width:100%;}
    .box-show{
        background:rgba(0,145,234,0.7);
        padding:10px;
        box-sizing:border-box;
        overflow: hidden;
        border-bottom: 2px solid #fff;
        width:31.33%;
        margin:0px 1%;
        float:left;
        height: 330px;
    }
    span{cursor: pointer;}
</style>
<script>
    import Products from './data.json';
    export default{
        data(){
            return{

                products:Products
            }
        },
        methods:{
            checkRating:function(index,key){
                this.products[index].categories[key].rating++;
                this.products[index].categories[key].check=false;
            },
            checkLike:function(index,key){
                this.products[index].categories[key].favorites[0].like++;
            },
            checkUnLike:function(index,key){
                this.products[index].categories[key].favorites[0].unlike++;
            }
        }
    }
</script>
  

Các bạn có thể chạy đoạn code và xem thử, hoặc bạn thêm nhiều mảng đối tượng để làm quen với for dữ liệu mảng đối tượng ra, vì sao này các ứng dụng toàn sử dụng mảng đối tượng json để làm ứng dụng. Hẹn mọi người bài viết chia sẻ sao nhé!

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)