vue 2.0 watch 監聽對象的變化


導讀

使用 Vue 中的 watch 方法監聽對象,設置 deep:true 可以進行深度監聽,當對象中的屬性發生變化時,會調用 handler 方法。

<template>
    <div>
        <input v-model="test.text">
    </div>
</template>
  
<script>
export default {
    data () {
        return {
            test: {
                text: ''
            }
        }
    },
  
    watch:{
        test: {
            deep: true,
            handler: function (newVal,oldVal){
                console.log('newValue', newVal);
                console.log('oldValue', oldVal.text);
            }
        }
    }
}
</script>

如果需要只監聽對象中某一屬性的變化,watch 也能實現,另外也可以結合使用計算屬性 computed 來對此進行監聽。

<script>
export default {
    data () {
        return {
            test: {
                text1: '',
                text2: ''
            }
        }
    },
    
    watch:{
        'test.text1': {
            deep: true,
            handler: function (newVal,oldVal){
                // code
            }
        }
    }
}
</script>

以下是結合計算屬性對某一對象的單一屬性實現監聽的方法:

<script>
export default {
    data () {
        return {
            test: {
                text1: '',
                text2: ''
            }
        }
    },
    computed:{
        testText1 () {
            return this.test.text1
        }
    },
    watch:{
        testText1: {
            dosomething (newVal,oldVal){
                // code
            }
        }
    }
}
</script>
寫在最后

如果文中有什么錯誤,歡迎大家指正,我們不怕錯,就怕錯不知。感謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM