<!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>Document</title>
</head>
<body>
<div id="app">
<!-- <input type="text" v-model.number="a"/>
<input type="text" v-model.number="b"/>
<p>之和:{{c}}</p> -->
<input type="text" v-model="obj.name"/>
<input type="text" v-model="obj.age"/>
<input type="text" v-model="obj.sex">
<hr>
<button @click="handlepush()">增加</button>
</div>
</body>
</html>
<script src="./vue.js"></script>
<script>
var vm = new Vue({
el:"#app",
data:{
a:"",
b:"",
c:"",
obj:{
name:"zhangsan",
age:19
},
arr:[10,20,30,40]
},
computed:{},
beforeMount(){
// this.obj.sex="女"
this.$set(this.obj,"sex","女")
},
methods:{
handlepush(){
// this.arr.length = 0;
// console.log(this.arr);
// this.arr[0] = 100;
// console.log(this.arr);
this.$set(this.arr,0,100);
}
},
watch:{
// "obj.name"(newVal,oldVal){
// console.log(newVal,oldVal)
// },
// "obj.age"(newVal,oldVal){
// console.log(newVal,oldVal)
// }
// obj:{
// handler(newVal){
// console.log(newVal)
// },
// deep:true,
// //當頁面第一次加載的時候也會做監聽
// immediate:true
// }
arr(newVal){
console.log(newVal)
}
}
})
/*
屬性監聽
watch:監聽屬性的變化
原理:
監聽依賴的屬性,當依賴的屬性發生改變的時候,當前函數就會被調用
注意:
1、watch對象中存放的都是函數,函數的名稱是data中的key值
2、當data的屬性發生改變的時候,那么watch中的函數就會執行。watch中的函數不需要調用
3、watch中的函數會接收到2個值 一個是新值一個是舊值
4、watch(watch如果監聽對象的情況下只會監聽對象的地址有沒有發生改變)如果想要監聽對象的情況下,必須進行深度監聽
5、如果需要進行深度監聽的時候必須使用handler函數以及設置deep為true
6、在特殊的情況下watch是無法監聽數組的變化,我們可以通過this.$set進行數據的修改
7、watch默認情況下第一次頁面加載的時候是不會進行數據的監聽的,如果設置immediate就可以在第一次加載頁面的時候進行數據的監聽
核心:
當一個屬性影響多個屬性影響的時候就需要用到watch (搜索框 城市選擇 vip級別選擇....)
能用computed解決的不要用watch
面試題:
在watch中如何監聽數組的變化?
通過set進行數組的更改
*/
</script>