1. 程式人生 > 實用技巧 >v-for中key的作用

v-for中key的作用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        .userList {
            border: 1px solid red;
            margin: 10px auto;
            padding: 10px 10px;
        }
    </style>
</head>
<
body> <div id="app"></div> <script src="./vue.js"></script> <script src='./lodash.min.js'></script> <script> Vue.component('my-com', { template: ` <div class="userList"> <div class
="content"> <h3>{{ obj.name }}</h3> <p>{{ obj.content }}</p> </div> <div> <input placeholder='請輸入您的姓名'> <
/div> </div> `, props: { obj: Object } }) var App = { data(){ return { datas: [ {id: 1, name: 'Sunny', content: 'I am Sunny!'}, {id: 2, name: 'Jerry', content: 'I am Jerry!'}, {id: 3, name: 'Tommy', content: 'I am Tommy!'}, {id: 4, name: 'Marry', content: 'I am Marry!'}, ] } }, template: ` <div> <button v-on:click='change'>改變順序</button> <my-com v-for = '(item,index) in datas' :obj = 'item' :key = 'item.id'></my-com> </div> `, methods: { change: function(){ this.datas = _.shuffle(this.datas) } } } new Vue({ el: '#app', template: ` <App /> `, components: { App } }) </script> </body> </html>