vue中watch如何同時監(jiān)聽多個屬性
vue watch同時監(jiān)聽多個屬性
1. watch監(jiān)聽的多個屬性之間沒有聯(lián)系(name、list),各自監(jiān)聽值改變后執(zhí)行各自的方法,也無關順序問題;
watch:{ name(newValue, oldValue) { this.name = newValue }, list(newVal, oldVal) { this.list = newVal } }
2. watch監(jiān)聽的多個屬性之間相互有聯(lián)系(useableCardTypeTime、tableData),并且任何一個值改變都有可能對第三個值(addDisable)產(chǎn)生改變,所以監(jiān)聽兩個屬性的方法中都需要寫對第三個值的改變操作;
watch:{ useableCardTypeTime(newValue, oldValue) { if(this.tableData.length >= newValue.length) { this.addDisable = true } else { this.addDisable = false } }, tableData(newVal, oldVal) { if(newVal.length >= this.useableCardTypeTime.length) { this.addDisable = true } else { this.addDisable = false } } }
對于以上多個屬性之間有關聯(lián)的問題,還有一個更為簡便的方式來解決,即:
使用 computed 和 watch 監(jiān)聽相結(jié)合的方式(推薦):
computed: { listenChange () { const { useableCardTypeTime, tableData } = this return { useableCardTypeTime, tableData } } }, watch:{ listenChange (val) { if(val.tableData.length >= val.useableCardTypeTime.length) { this.addDisable = true } else { this.addDisable = false } } }
對于項目中需要一次性監(jiān)聽多個屬性值的變化時,推薦大家使用最后一種方式喔~~~(computed 和 watch 相結(jié)合)
vue watch深度監(jiān)聽多個屬性實例
watch :{ //監(jiān)聽type的變化 'temp.type': { handler(type,old) { //這里寫你的業(yè)務邏輯 console.log('obj.a changed', type); if (type == 1) { this.temp.title = '速來↓↓↓' } else { this.temp.title = '' } }, immediate: true, // deep: true }, 'temp.liveName': { handler(liveName,old) { //這里寫你的業(yè)務邏輯 console.log('obj.a changed', liveName); if (this.temp.type == 1) { this.temp.title = " 速來↓↓↓" } }, immediate: true, // deep: true } },
watch中的immediate、handler和deep屬性
(1)immediate和handler
這樣使用watch時有一個特點,就是當值第一次綁定時,不會執(zhí)行監(jiān)聽函數(shù),只有值發(fā)生改變時才會執(zhí)行。
如果我們需要在最初綁定值的時候也執(zhí)行函數(shù),則就需要用到immediate屬性。
(2)deep
當需要監(jiān)聽一個對象的改變時,普通的watch方法無法監(jiān)聽到對象內(nèi)部屬性的改變,此時就需要deep屬性對對象進行深度監(jiān)聽。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue axios數(shù)據(jù)請求get、post方法及實例詳解
axios是一個基于Promise,同時支持瀏覽器端和Node.js的HTTP庫,常用于Ajax請求。這篇文章主要介紹了vue axios數(shù)據(jù)請求get、post方法的使用 ,需要的朋友可以參考下2018-09-09el-table多選toggleRowSelection不生效解決方案
這篇文章主要給大家介紹了關于el-table多選toggleRowSelection不生效的解決方案,文中通過圖文以及代碼將解決辦法介紹的非常詳細,需要的朋友可以參考下2023-08-08vue element-ui el-tooltip組件失效問題及解決
這篇文章主要介紹了vue element-ui el-tooltip組件失效問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10vuex 解決報錯this.$store.commit is not a function的方法
這篇文章主要介紹了vuex 解決報錯this.$store.commit is not a function的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12