一、文字总结
1、Vue会监视data中所有层次的数据
2、如何监测对象中的数据?
通过setter实现监视,且要在new Vue时就传入要监测的数据
(1)对象中后追加的属性,Vuem默认不做响应式处理
(2)如需给后添加的属性做相应式,请使用如下API:
Vue.set(target,propertyName/index,value)
或vm.$set(target,propertyName/index,value)
3、如何监测数组中的对象?
通过包裹数组更新元素的方法实现,本质做了两件事:
(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 lang="en">
<head>
<title>practice</title>
<script src="vue.js"></script>
</head>
<body>
<div id="root">
<h1>学生信息</h1>
<button @click="student.age++">年龄+1岁</button><br/><br/>
<button @click="addSex">添加性别属性,默认值:女</button><br/><br/>
<button @click="addFriend">在列表首位添加一个朋友</button><br/><br/>
<button @click="updateFirstFriend">修改第一个朋友的名字为:lily</button><br/><br/>
<button @click="addHobby">添加一个爱好</button><br/><br/>
<button @click="updateFirstHobby">修改第一个爱好为:阅读</button><br/><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) of student.hobby" :key="index">
{{h}}
</li>
</ul>
<h3>朋友们:</h3>
<ul>
<li v-for="(f,index) of student.friends" :key="index">
{{f.name}}-{{f.age}}
</li>
</ul>
</body>
<script type="text/javascript">
Vue.config.productionTip=false
new Vue({
el:'#root',
data:{
student:{
name:'jack',
age:18,
hobby:['打游戏','听歌','看动漫'],
friends:[
{name:'tom',age:19},
{name:'mark',age:16},
{name:'mary',age:17}
]
}
},
methods:{
addSex(){
Vue.set(this.student,'sex','女')
},
addFriend(){
this.student.friends.unshift(
{name:'bob',age:20})
},
updateFirstFriend(){
this.student.friends[0].name='lily'
},
addHobby(){
this.student.hobby.push('玩滑板')
},
updateFirstHobby(){
this.student.hobby.splice(0,1,'阅读')
}
}
})
</script>
</html>