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í)行(默認(rèn)) | 強制效果始終同步觸發(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 效果一樣文章來源:http://www.zghlxwxcb.cn/news/detail-737431.html
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 單一值文章來源地址http://www.zghlxwxcb.cn/news/detail-737431.html
import { ref, watch ,reactive} from 'vue'
let message = reactive({
name:"",
name2:""
})
watch(()=>message.name, (newVal, oldVal) => {
console.log('新的值----', newVal);
console.log('舊的值----', oldVal);
}
到了這里,關(guān)于Vue中watch偵聽器用法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!