一文搞懂Vue中watch偵聽器的用法
watch 需要偵聽特定的數(shù)據(jù)源,并在單獨的回調(diào)函數(shù)中執(zhí)行副作用
watch第一個參數(shù)監(jiān)聽源
watch第二個參數(shù)回調(diào)函數(shù)cb(newVal,oldVal)
watch第三個參數(shù)一個options配置項是一個對象{
immediate:true //是否立即調(diào)用一次
deep:true //是否開啟深度監(jiān)聽
flush:“pre” // 更新時機
}
flush配置項
pre | sync | post |
---|---|---|
組件更新前執(zhí)行(默認) | 強制效果始終同步觸發(fā) | 組件更新后執(zhí)行 |
1. 監(jiān)聽Ref 案例
import { ref, watch } from 'vue' let message = ref({ nav:{ bar:{ name:"" } } }) watch(message, (newVal, oldVal) => { console.log('新的值----', newVal); console.log('舊的值----', oldVal); },{ immediate:true, deep:true })
監(jiān)聽多個ref 注意變成數(shù)組
import { ref, watch ,reactive} from 'vue' let message = ref('') let message2 = ref('') watch([message,message2], (newVal, oldVal) => { console.log('新的值----', newVal); console.log('舊的值----', oldVal); })
2. 監(jiān)聽Reactive
使用reactive監(jiān)聽深層對象開啟和不開啟deep 效果一樣
import { ref, watch ,reactive} from 'vue' let message = reactive({ nav:{ bar:{ name:"" } } }) watch(message, (newVal, oldVal) => { console.log('新的值----', newVal); console.log('舊的值----', oldVal); })
監(jiān)聽reactive 單一值
import { ref, watch ,reactive} from 'vue' let message = reactive({ name:"", name2:"" }) watch(()=>message.name, (newVal, oldVal) => { console.log('新的值----', newVal); console.log('舊的值----', oldVal); }
以上就是一文搞懂Vue中watch偵聽器的用法的詳細內(nèi)容,更多關(guān)于Vue watch偵聽器的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue+elementui 表格分頁限制最大頁碼數(shù)的操作代碼
這篇文章主要介紹了vue+elementui 表格分頁限制最大頁碼數(shù)的操作代碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-08-08vue-electron項目創(chuàng)建記錄及問題小結(jié)解決方案
這篇文章主要介紹了vue-electron項目創(chuàng)建記錄及注意事項,本文給大家分享了運行項目報錯的問題小結(jié)及多種解決方案,需要的朋友可以參考下2024-03-03vuejs實現(xiàn)標簽選項卡動態(tài)更改css樣式的方法
這篇文章主要介紹了vuejs實現(xiàn)標簽選項卡-動態(tài)更改css樣式的方法,代碼分為html和js兩部分,需要的朋友可以參考下2018-05-05前端實現(xiàn)Vue組件頁面跳轉(zhuǎn)的多種方式小結(jié)
這篇文章主要為大家詳細介紹了前端實現(xiàn)Vue組件頁面跳轉(zhuǎn)的多種方式,文中的示例代碼講解詳細,具有一定的參考價值,有需要的小伙伴可以了解下2024-02-02