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