v-for遍历数组完成列表渲染需要注意的问题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<!--
1. 列表显示
  数组: v-for / index
  对象: v-for / key
2. 列表的更新显示
  删除item
  替换item
-->
    <div id="app">
        <h2>1,测试v-for遍历数组</h2>
        <ul>
            <li v-for='(p,index) in persons' :key="index">{{index}}--{{p.name}}--{{p.age}}
                --<button @click="deleteP(index)">删除</button>
                --<button @click="updateP(index,{name:'Cat',age:22})">更新</button>
            </li>  
        </ul>
    </div>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript">
        new Vue({
            el:'#app',
            data:{
                persons:[
                    {name:'Bob',age:19},
                    {name:'Jane',age:17},
                    {name:'Mike',age:18},
                    {name:'Son',age:20}
                ]
            },
            methods:{
                deleteP(index){
                  this.persons.splice(index,1)  
                },
                updateP(index,newP){
                    //内存里的persons里的数据变了,但是页面无法更新,没有实现数据绑定的功能,因此还是要用splice方法
                    // this.persons[index]=newP
                    this.persons.splice(index,1,newP)
                }
            }
        })
    </script>

当更新数组时,不能直接重新给数组重新赋值,虽然内存中persons里的数据改变了,但是页面无法更新,没有实现数据绑定的功能,因此还是要用splice方法。

Vue本身只是监视了persons的改变,没有监视数组内部数据的改变
Vue重写了数组中的一系列改变数组内部数据的方法(先调用原生,再更新界面)--->数组内部改变,界面自动变化,实现了数据绑定的功能,比如有push(),pop(),shift(),unshift(),splice(),sort(),reverse(),这些方法将会观察数组的变异,然后触发视图的变化。

猜你喜欢

转载自blog.csdn.net/qq_40885461/article/details/88702327