1. 程式人生 > 實用技巧 >Vue中watch高階用法

Vue中watch高階用法

1. 不依賴新舊值的watch

很多時候,我們監聽一個屬性,不會使用到改變前後的值,只是為了執行一些方法,這時可以使用字串代替

data:{
    name:'Joe'
},
watch:{
    name:'sayName'
},
methods:{
    sayName(){
        console.log(this.name)
    }
}

2.立即執行watch

總所周知,watch是在監聽屬性改變時才會觸發,有些時候,我們希望在元件建立後watch能夠立即執行一次。可能想到的的方法就是在create生命週期中呼叫一次,但這樣的寫法不優雅,或許我們可以使用這樣的方法

data:{
    name:'Joe'
},
watch:{
    name:{
        handler: 'sayName',
        immediate: true
    }
},
methods:{
    sayName(){
        console.log(this.name)
    }
}

上面我們給入一個物件

handelr: 觸發監聽執行的方法(需要用到改變前後的值時,可換成函式)
immediate: 監聽開始之後被立即呼叫

3. 深度監聽

在監聽一個物件時,當物件內部的屬性被改變時,無法觸發watch,我們可以繼續使用物件的方式為其設定深度監聽

data:{
    studen: {
        name:'Joe',
        skill:{
            run:{
                speed: '5m/s'
            }
        }
    }
},
watch:{
    studen:{
        handler: 'sayName',
        deep: true
    }
},
methods:{
    sayName(){
        console.log(this.studen)
    }
}

設定deep為true後,無論巢狀多深,只要屬性值被改變都會觸發監聽

廣州品牌設計公司https://www.houdianzi.com PPT模板下載大全https://redbox.wode007.com

4.監聽執行多個方法

使用陣列可以設定多項,形式包括字串、函式、物件

data:{
    name:'Joe'
},
watch:{
    name:[
        'sayName1',
        function(newVal, oldVal){
              this.sayName2()
        },
        {
            handler: 'sayName3',
            immaediate: true
        }
    ]
},
methods:{
    sayName1(){
        console.log('sayName1==>', this.name)
    },
    sayName2(){
        console.log('sayName2==>', this.name)
    },
    sayName3(){
        console.log('sayName3==>', this.name)
    },
}