Vue监视数据的原理

1. vue会监视data中所有层次的数据。

2. 如何监测对象中的数据?

通过setter实现监视,且要在new Vue时就传入要监测的数据。
(1).对象中后追加的属性,Vue默认不做响应式处理
(2).如需给后添加的属性做响应式,请使用如下API:
Vue.set(target,propertyName/index,value) 或
vm.$set(target,propertyName/index,value)

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

通过包裹数组更新元素的方法实现,本质就是做了两件事:
(1).调用原生对应的方法对数组进行更新。
(2).重新解析模板,进而更新页面。

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

否则vue无法监测到数据变化,页面就不会跟着改变
1.使用这些API:push()、pop()、shift()、unshift()、splice()、sort()、reverse()
2.Vue.set() 或 vm.$set()

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

示例:

data:{
	student:{
		name:'tom',
		age:18,
		hobby:['抽烟','喝酒','烫头'],
		friends:[
			{name:'jerry',age:35},
			{name:'tony',age:36}
			]
		}
  }
//需求:给student增加一个性别为男的属性
   //方法1
   Vue.set(this.student,'sex','男')
   //方法2
   this.$set(this.student,'sex','男')

//需求:给friends开头增加一个朋友
  this.student.friends.unshift({name:'jack',age:70})

//更改friends 第一个对象的name
  this.student.friends[0].name = '张三'

//hobby新增一个内容
  this.student.hobby.push('学习')

//更新hobby第一项内容
  /方法1
  this.student.hobby.splice(0,1,'开车')
  //方法2
  Vue.set(this.student.hobby,0,'开车')
  //方法3
  this.$set(this.student.hobby,0,'开车')

//过滤掉hobby 中的抽烟
//这里我们需要用到filter 但是这个函数不被vue监视,我们需要把过滤后的数据再赋值给原来的数据就可以了
  this.student.hobby = this.student.hobby.filter((h)=>{
			return h !== '抽烟'
			})
原文地址:https://www.cnblogs.com/qingheshiguang/p/15016409.html