Vue中的数据监测

179 阅读1分钟

Vue把data中每一组key,value都加加工成了getter ,setter的写法。name的值不是直接获取的,是通过get获取的。当修改name 的时候会调用set。

image.png

Vue监视数据的原理:

  1. vue会监视data中所有层次的数据。
  2. 如何监测对象中的数据? 通过setter实现监视,且要在new Vue时就传入要监测的数据。
  • (1).对象中后追加的属性,Vue默认不做响应式处理
  • (2).如需给后添加的属性做响应式,请使用如下API: Vue.set(target,propertyName/index,value) 或 vm.$set(target,propertyName/index,value)
  1. 如何监测数组中的数据? 通过包裹数组更新元素的方法实现,本质就是做了两件事:
  • (1).调用原生对应的方法对数组进行更新。
  • (2).重新解析模板,进而更新页面。

4.在Vue修改数组中的某个元素一定要用如下方法:

  • 1.使用这些API:push()、pop()、shift()、unshift()、splice()、sort()、reverse()
  • 2.Vue.set() 或 vm.$set()

特别注意:Vue.set() 和 vm.$set() 不能给vm 或 vm的根数据对象 添加属性!!!

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>总结数据监视</title>
		<style>
			button{
				margin-top: 10px;
			}
		</style>
		<!-- 引入Vue -->
		<script type="text/javascript" src="../js/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="updateFirstFriendName">修改第一个朋友的名字为:张三</button> <br/>
			<button @click="addHobby">添加一个爱好</button> <br/>
			<button @click="updateHobby">修改第一个爱好为:开车</button> <br/>
			<button @click="removeSmoke">过滤掉爱好中的抽烟</button> <br/>
			<h3>姓名:{{student.name}}</h3>
			<h3>年龄:{{student.age}}</h3>
			<h3 v-if="student.sex">性别:{{student.sex}}</h3>
			<h3>爱好:</h3>
			<ul>
				<li v-for="(h,index) in student.hobby" :key="index">
					{{h}}
				</li>
			</ul>
			<h3>朋友们:</h3>
			<ul>
				<li v-for="(f,index) in student.friends" :key="index">
					{{f.name}}--{{f.age}}
				</li>
			</ul>
		</div>
	</body>

	<script type="text/javascript">
		Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

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

image.png

2. 数组更新检测

  • Vue 重写了数组中的一系列改变数组内部数据的方法(先调用原生,再更新界面)

image.png

this.persons[index] = new P;
//并没有改变persons本身,数组内部发生了变化,但是没有调用变异方法,vue不会更新界面

也可以替换item
相比之下,也有非变更方法,例如 filter()、concat() 和 slice()。它们不会变更原始数组,而总是返回一个新数组。当使用非变更方法时,可以用新数组替换旧数组。

let fpersons = persons.filter(
  p => p.name.includes(searchName)
)
<body>
    <div id="demo">
        <h2>测试: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: 20})">更新</button>
            </li>
        </ul>

        <h2>测试:v-for遍历对象</h2>
        <ul>
            <li v-for="(value, key) in persons[1]" :key="key">
                {{value}}---{{key}} 
            </li>
        </ul>

    </div>
    
    <script src="../js/vue.js"></script>
    <script>
        // Vue本身只是监视了persons的改变,没有监视数组内部数据的改变
        // Vue 重写了数组中的一系列改变数组内部数据的方法(先调用原生,再更新界面)
        new Vue({
            el: '#demo',
            data: {
                persons:[ 
                    {name: 'Tom', age: 18},
                    {name: 'Jack', age: 19},
                    {name: 'Marry', age: 16},
                    {name: 'Rose', age: 12},
                ]
            },
            methods: {
                deleteP(index){
                    // 删除persons中指定idnex的p(有数据绑定)
                    this.persons.splice(index, 1);
                },
                updateP(index, newP){
                    // this.persons[index] = newP; //数据(数组内部)变了,界面没有变化(没有数据绑定)
                    //并没有改变persons本身,数组内部发生了变化,但是没有调用变异方法,vue不会更新界面
                    // this.persons = []  //界面有变化,改变了persons
                    this.persons.splice(index, 1, newP);
                }
            }
        })
    </script>
</body>