- vue會監視data中所有層次的資料。
-
如何監測對象中的資料?
通過setter實作監視,且要在new Vue時就傳入要監測的資料。
1. 對象中後追加的屬性,Vue預設不做響應式處理
2. 如需給後添加的屬性做響應式,請使用如下API:
Vue.set(target,property/index,value)
this.$set(target,property/index,value)
-
如何監測數組中的資料?
通過包括數組更新元素的方法實作,本質就是做了兩件事:
- 調用原生對應的方法對數組進行更新
- 重新解析模闆,進而更新頁面。
- 在vue修改數組中的某個元素一定要用如下方法:
- 使用這些API:push()、pop()、unshift()、splice()、sort()、reverse()
- 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>