天天看点

Vue监视数据原理

  1. vue会监视data中所有层次的数据。
  2. 如何监测对象中的数据?

    通过setter实现监视,且要在new Vue时就传入要监测的数据。

    1. 对象中后追加的属性,Vue默认不做响应式处理

    2. 如需给后添加的属性做响应式,请使用如下API:

    Vue.set(target,property/index,value)

    this.$set(target,property/index,value)

  3. 如何监测数组中的数据?

    通过包括数组更新元素的方法实现,本质就是做了两件事:

    1. 调用原生对应的方法对数组进行更新
    2. 重新解析模板,进而更新页面。
  4. 在vue修改数组中的某个元素一定要用如下方法:
    1. 使用这些API:push()、pop()、unshift()、splice()、sort()、reverse()
    2. Vue.set()或this. s e t ( ) 特 别 注 意 : V u e . s e t ( ) 和 t h i s . set() 特别注意:Vue.set() 和 this. set()特别注意:Vue.set()和this.set() 不能给vm或vm的根数据对象添加属性
<!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>vue监测数据改变的原理</title>
  <script src="../vue.js"></script>
</head>
<body>
  <div id="root">
    <h1>学生信息</h1>

    <button @click='student.age++'>年龄+1岁</button><br>
    <button @click='addSex'>添加行呗属性,默认值:男</button><br>
    <button @click='student.sex = "未知"'>修改性别</button><br>
    <button @click='addFriend'>在列表首位添加一个朋友</button><br>
    <button @click='updateFirstFriendMessage'>修改第一个朋友的名字为张三</button><br>
    <button @click='addHobby'>添加一个爱好</button><br>
    <button @click='updateHobby'>修改第一个爱好为开车</button><br>

    <p>学生姓名:{{student.name}}</p>
    <p v-if='student.sex != null'>学生性别:{{student.sex}}</p>
    <p>学生年龄:{{student.age}}</p>
    <h2>爱好</h2>
    <ul>
      <li v-for="item in student.hobby">
        {{item}}
      </li>
    </ul>
    <h2>朋友信息</h2>
    <ul>
      <li v-for="item in student.friends">
        {{item.name}}--{{item.age}}
      </li>
    </ul>
  </div>

  <script>
    Vue.config.productionTip=false

    const vm = new Vue({
      el: '#root',
      data: {
        student: {
          name: 'tom',
          age: 18,
          hobby:['抽烟','喝酒','烫头'],
          friends: [
            {name:'jerry',age:35},
            {name:'tony',age:36},
            {name:'tom',age:31}
          ]
        }
      },
      methods:{
        addSex() {
          // Vue.set(this.student,'sex','男')
          this.$set(this.student, 'sex', '男')
        },
        addFriend() {
          this.student.friends.unshift({name:'jack',age:17})
        },
        updateFirstFriendMessage() {
          this.student.friends[0].name = '张三'
          this.student.friends[0].age = 5
        },
        addHobby() {
          this.student.hobby.push('学习')
        },
        updateHobby () {
          // this.student.hobby.splice(0,1,'开车')
          Vue.set(this.student.hobby,0,'开车')
        }
      }
    })
  </script>
</body>
</html>
           

继续阅读