Vue屬性監聽

<!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:監聽屬性的變化 原理: 監聽依賴的屬性,當依賴的屬性發生改變的時候,當前函數就會被調用 注意: 一、watch對象中存放的都是函數,函數的名稱是data中的key值 二、當data的屬性發生改變的時候,那麼watch中的函數就會執行。watch中的函數不須要調用 三、watch中的函數會接收到2個值 一個是新值一個是舊值 四、watch(watch若是監聽對象的狀況下只會監聽對象的地址有沒有發生改變)若是想要監聽對象的狀況下,必須進行深度監聽 五、若是須要進行深度監聽的時候必須使用handler函數以及設置deep爲true 六、在特殊的狀況下watch是沒法監聽數組的變化,咱們能夠經過this.$set進行數據的修改 七、watch默認狀況下第一次頁面加載的時候是不會進行數據的監聽的,若是設置immediate就能夠在第一次加載頁面的時候進行數據的監聽 核心: 當一個屬性影響多個屬性影響的時候就須要用到watch (搜索框 城市選擇 vip級別選擇....) 能用computed解決的不要用watch 面試題: 在watch中如何監聽數組的變化? 經過set進行數組的更改 */
</script>
相關文章
相關標籤/搜索