詳解Vue3中的watch偵聽器和watchEffect高級偵聽器
1watch偵聽器
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)聽
- }
監(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);
})監(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);
})2watchEffect高級偵聽器
立即執(zhí)行傳入的一個函數(shù),同時響應(yīng)式追蹤其依賴,并在其依賴變更時重新運行該函數(shù)。如果用到message 就只會監(jiān)聽message 就是用到幾個監(jiān)聽幾個 而且是非惰性 會默認調(diào)用一次。
let message = ref<string>('')
let message2 = ref<string>('')
watchEffect(() => {
//console.log('message', message.value);
console.log('message2', message2.value);
})清除副作用:就是在觸發(fā)監(jiān)聽之前會調(diào)用一個函數(shù)可以處理你的邏輯例如防抖
import { watchEffect, ref } from 'vue'
let message = ref<string>('')
let message2 = ref<string>('')
watchEffect((oninvalidate) => {
//console.log('message', message.value);
oninvalidate(()=>{
})
console.log('message2', message2.value);
})停止跟蹤 watchEffect 返回一個函數(shù) 調(diào)用之后將停止更新
const stop = watchEffect((oninvalidate) => {
//console.log('message', message.value);
oninvalidate(()=>{
})
console.log('message2', message2.value);
},{
flush:"post",// pre:組件更新前執(zhí)行;sync:強制效果始終同步觸發(fā),post:組件更新后執(zhí)行
onTrigger () { //onTrigger 可以幫助我們調(diào)試 watchEffect
}
})
stop()到此這篇關(guān)于Vue3中的watch偵聽器和watchEffect高級偵聽器的文章就介紹到這了,更多相關(guān)Vue3watch偵聽器和watchEffect偵聽器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue watch偵聽器有無immediate的運行順序問題
這篇文章主要介紹了vue watch偵聽器有無immediate的運行順序問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08
監(jiān)聽element-ui table滾動事件的方法
這篇文章主要介紹了監(jiān)聽element-ui table滾動事件的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
vue中this.$router.push()路由傳值和獲取的兩種常見方法匯總
這篇文章主要介紹了vue中this.$router.push()路由傳值和獲取的兩種常見方法,本文結(jié)合示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-12-12
Vue使用Less與Scss實現(xiàn)主題切換方法詳細講解
目前,在眾多的后臺管理系統(tǒng)中,換膚功能已是一個很常見的功能。用戶可以根據(jù)自己的喜好,設(shè)置頁面的主題,從而實現(xiàn)個性化定制。目前,我所了解到的換膚方式,也是我目前所掌握的兩種換膚方式,想同大家一起分享2023-02-02

