v-for 中的 key

1、使用子数组循环输出一堆数据。

2、不依赖子组件状态或临时 DOM 状态(例如:表单输入值)的列表渲染输出。

3、建议 v-for 就加上 key,提升性能,避免 vue 运算, key 就是记录元素与 DOM 间的位置关系。

案例:

1、创建一个 my-com 全局组件,在全局组件中使用 props 属性接收父组件的值。

Vue.component('my-com',{
  template:` 
    <div class='userList'>
      <div class='content'>
        <h3>{{obj.name}}</h3>
          <p>{{obj.content}}</p>
      </div>
      <div class="control">
        <input type="text" placeholder='请输入你的名字'>
      </div>
    </div>
  `,
  props:{
    // 接收父组件传过来的属性
    obj: Object
  }
});

2、创建一个 App 组件,在App 组件内调用 my-com 组件,并将数据通过 v-bind 将结果绑定到 obj 中。

<my-com v-for='(item,index) in datas' :obj='item' :key='item.id' />

3、在 App 组件中绑定点击事件,当点击事件发生时,调用  _.shuffle 创建一个打乱顺序的数组。

change(){
    this.datas = _.shuffle(this.datas);
}

css 代码:

    <style type="text/css">
        .userList{
            border: 1px solid red;
            margin: 20px 0;
            padding: 10px 10px;
        }
    </style>

js 代码:

    <script type="text/javascript">
        Vue.component('my-com',{
            template:` 
                <div class='userList'>
                    <div class='content'>
                        <h3>{{obj.name}}</h3>
                        <p>{{obj.content}}</p>
                    </div>
                    <div class="control">
                        <input type="text" placeholder='请输入你的名字'>
                    </div>
                </div>
            `,
            props:{
                // 接收父组件传过来的属性
                obj: Object
            }
        });
        var App = {
            data(){
                return{
                    datas:[
                        {id:1, name:'张三', content:'我是张三'},
                        {id:2, name:'李四', content:'我是李四'},
                        {id:3, name:'王五', content:'我是王五'}
                    ]
                }
            },
            template:`
                <div>
                    <button @click='change'>改变顺序</button>

                    <my-com v-for='(item,index) in datas' :obj='item' :key='item.id' />
                </div>
            `,
            methods:{
                change(){
                    this.datas = _.shuffle(this.datas);
                }
            }
        };
        new Vue({
            el:'#app',
            template:` 
                <App/>
            `,
            components:{
                App
            }
        });
    </script>

 

posted @ 2022-11-21 07:23  炒股沦为首负  阅读(36)  评论(0编辑  收藏  举报