一文搞懂Vue中watch偵聽器的用法
watch 需要偵聽特定的數據源,并在單獨的回調函數中執(zhí)行副作用
watch第一個參數監(jiān)聽源
watch第二個參數回調函數cb(newVal,oldVal)
watch第三個參數一個options配置項是一個對象{
immediate:true //是否立即調用一次
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 注意變成數組
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偵聽器的用法的詳細內容,更多關于Vue watch偵聽器的資料請關注腳本之家其它相關文章!
相關文章
Vue?中ref()和?reactive()響應式數據的使用方法
article介紹Vue3中ref()和reactive()函數的使用方法,ref()用于創(chuàng)建基本數據類型的響應式引用,reactive()用于創(chuàng)建響應式對象,本文介紹Vue中ref()和reactive()響應式數據的使用方法,感興趣的朋友一起看看吧2025-01-01
解決創(chuàng)建vue項目后沒有vue.config.js文件的問題
這篇文章給大家主要介紹如何解決創(chuàng)建vue項目后沒有webpack.config.js(vue.config.js)文件,文中有詳細的解決方法,感興趣的朋友可以參考閱讀下2023-07-07
Ant Design Vue resetFields表單重置不生效問題及解決
這篇文章主要介紹了Ant Design Vue resetFields 表單重置不生效問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
vue最強table vxe-table 虛擬滾動列表 前端導出問題分析
最近遇到個問題,后臺一次性返回2萬條列表數據并且需求要求所有數據必須全部展示,不能做假分頁,怎么操作呢,下面通過本文介紹下vue最強table vxe-table 虛擬滾動列表 前端導出問題,感興趣的朋友一起看看吧2023-10-10

