詳解Vue3中Watch監(jiān)聽事件的使用
一、watch的使用
watch(WatcherSource, Callback, [WatchOptions]) type WatcherSource<T> = Ref<T> | (() => T) interface WatchOptions extends WatchEffectOptions { -- deep?: boolean ``// 默認(rèn):false` -- immediate?: boolean ``// 默認(rèn):false` }
參數(shù)說明:
- WatcherSource: 用于指定要偵聽的響應(yīng)式變量。WatcherSource可傳入ref響應(yīng)式數(shù)據(jù),reactive響應(yīng)式對象要寫成函數(shù)的形式。
- Callback: 執(zhí)行的回調(diào)函數(shù),可依次接收當(dāng)前值newValue,先前值oldValue作為入?yún)ⅰ?/li>
- WatchOptions:支持 deep、immediate。當(dāng)需要對響應(yīng)式對象進(jìn)行深度監(jiān)聽時,設(shè)置deep: true;默認(rèn)情況下watch是惰性的,當(dāng)我們設(shè)置immediate: true時,watch會在初始化時立即執(zhí)行回調(diào)函數(shù)。
- 除此之外,vue3的watch還支持偵聽多個響應(yīng)式數(shù)據(jù),也能手動停止watch監(jiān)聽。
1、引入watch
import { watch } from 'vue'
然后在setup里注入監(jiān)聽事件
setup(props){ const state = reactive({ count: 0 , message:'Hellow world' }); watch(state,()=>{ console.log(state.count); --單個監(jiān)聽 }) return { state, } },
2、多個數(shù)據(jù)源監(jiān)聽
<template> <div> age: {{obj1.age}} name: {{obj.name}} list: <ul> <li v-for="(item, index) in obj.list" :key="index"> {{item}} </li> </ul> <hr> <button @click="changeName">改變name</button> <button @click="changeList">改變list</button> <button @click="changeAge">改變age</button> </div> </template> <script lang="ts"> import {defineComponent, reactive, watch} from 'vue'; export default defineComponent({ setup () { let obj = reactive({ name: '1111', list: ['222', '222222', '222222'] }) let obj1 = reactive({ age: 18 }) function changeName () { obj.name += '+' } function changeList () { obj.list[0] += '+' } function changeAge () { obj1.age++ } watch([obj, obj1], () => { console.log(obj.name) if(obj.age>28){ watchFunc() // 停止監(jiān)聽` } }, { // 頁面加載會先執(zhí)行一次 immediate: true }) return { obj, changeName, changeList, changeAge, obj1 } } }) </script> <style scoped> </style>
結(jié)果:當(dāng)改變名字和年齡時,watch都監(jiān)聽到了數(shù)據(jù)的變化。當(dāng)age大于28時,我們停止了監(jiān)聽,此時再改變年齡,由于watch的停止,導(dǎo)致watch的回調(diào)函數(shù)失效。
解決辦法:我們可以通過watch偵聽多個值的變化,也可以利用給watch函數(shù)取名字,然后通過執(zhí)行名字()函數(shù)來停止偵聽。
3、監(jiān)聽數(shù)組變化
<template> <div class="watch-test"> <div>ref定義數(shù)組:{{arrayRef}}</div> <div>reactive定義數(shù)組:{{arrayReactive}}</div> </div> <div> <button @click="changeArrayRef">改變ref定義數(shù)組第一項</button> <button @click="changeArrayReactive">改變reactive定義數(shù)組第一項</button> </div> </template> <script> import {ref, reactive, watch} from 'vue' export default { name: 'WatchTest', setup() { const arrayRef = ref([1, 2, 3, 4]) const arrayReactive = reactive([1, 2, 3, 4]) //ref not deep const arrayRefWatch = watch(arrayRef, (newValue, oldValue) => { console.log('newArrayRefWatch', newValue, 'oldArrayRefWatch', oldValue) }) //ref deep const arrayRefDeepWatch = watch(arrayRef, (newValue, oldValue) => { console.log('newArrayRefDeepWatch', newValue, 'oldArrayRefDeepWatch', oldValue) }, {deep: true}) //reactive,源不是函數(shù) const arrayReactiveWatch = watch(arrayReactive, (newValue, oldValue) => { console.log('newArrayReactiveWatch', newValue, 'oldArrayReactiveWatch', oldValue) }) // 數(shù)組監(jiān)聽的最佳實(shí)踐- reactive且源采用函數(shù)式返回,返回拷貝后的數(shù)據(jù) const arrayReactiveFuncWatch = watch(() => [...arrayReactive], (newValue, oldValue) => { console.log('newArrayReactiveFuncWatch', newValue, 'oldArrayReactiveFuncWatch', oldValue) }) const changeArrayRef = () => { arrayRef.value[0] = 6 } const changeArrayReactive = () => { arrayReactive[0] = 6 } return { arrayRef, arrayReactive, changeArrayRef, changeArrayReactive } } } </script>
結(jié)果:當(dāng)將數(shù)組定義為響應(yīng)式數(shù)據(jù)ref時,如果不加上deep:true,watch是監(jiān)聽不到值的變化的;而加上deep:true,watch可以檢測到數(shù)據(jù)的變化,但老值和新值一樣,即不能獲取老值。當(dāng)數(shù)組定義為響應(yīng)式對象時,不作任何處理,watch可以檢測到數(shù)據(jù)的變化,但老值和新值一樣;如果把watch的數(shù)據(jù)源寫成函數(shù)的形式并通過擴(kuò)展運(yùn)算符克隆一份數(shù)組返回,就可以在監(jiān)聽的同時獲得新值和老值。
結(jié)論:定義數(shù)組時,最好把數(shù)據(jù)定義成響應(yīng)式對象reactive,這樣watch監(jiān)聽時,只需要把數(shù)據(jù)源寫成函數(shù)的形式并通過擴(kuò)展運(yùn)算符克隆一份數(shù)組返回,即可在監(jiān)聽的同時獲得新值和老值。
4、偵聽對象
<template> <div class="watch-test"> <div>user:{</div> <div>name:{{objReactive.user.name}}</div> <div>age:{{objReactive.user.age}}</div> <div>}</div> <div>brand:{{objReactive.brand}}</div> <div> <button @click="changeAge">改變年齡</button> </div> </div> </template> <script> import {ref, reactive, watch} from 'vue' import _ from 'lodash'; export default { name: 'WatchTest', setup() { const objReactive = reactive({user: {name: '小松菜奈', age: '20'}, brand: 'Channel'}) //reactive 源是函數(shù) const objReactiveWatch = watch(() => objReactive, (newValue, oldValue) => { console.log('objReactiveWatch') console.log('new:',JSON.stringify(newValue)) console.log('old:',JSON.stringify(oldValue)) }) //reactive,源是函數(shù),deep:true const objReactiveDeepWatch = watch(() => objReactive, (newValue, oldValue) => { console.log('objReactiveDeepWatch') console.log('new:',JSON.stringify(newValue)) console.log('old:',JSON.stringify(oldValue)) }, {deep: true}) // 對象深度監(jiān)聽的最佳實(shí)踐- reactive且源采用函數(shù)式返回,返回深拷貝后的數(shù)據(jù) const objReactiveCloneDeepWatch = watch(() => _.cloneDeep(objReactive), (newValue, oldValue) => { console.log('objReactiveCloneDeepWatch') console.log('new:',JSON.stringify(newValue)) console.log('old:',JSON.stringify(oldValue)) }) const changeAge = () => { objReactive.user.age = 26 } return { objReactive, changeAge } } } </script>
結(jié)果:當(dāng)把對象定義為響應(yīng)式對象reactive時,采用函數(shù)形式的返回,如果不加上deep:true,watch是監(jiān)聽不到值的變化的;而加上deep:true,watch可以檢測到數(shù)據(jù)的變化,但老值和新值一樣,即不能獲取老值;若把watch的數(shù)據(jù)源寫成函數(shù)的形式并通過深拷貝克?。ㄟ@里用了lodash庫的深拷貝)一份對象返回,就可以在監(jiān)聽的同時獲得新值和老值。
結(jié)論:定義對象時,最好把數(shù)據(jù)定義成響應(yīng)式對象reactive,這樣watch監(jiān)聽時,只需要把數(shù)據(jù)源寫成函數(shù)的形式并通過深拷貝克隆一份對象返回,即可在監(jiān)聽的同時獲得新值和老值。
5、結(jié)論
- 1.通常我們把原始類型的數(shù)據(jù)(number、string等)定義為ref響應(yīng)數(shù)據(jù),引用類型的數(shù)據(jù)(數(shù)組、對象)定義為reactive響應(yīng)式數(shù)據(jù);
- 2.當(dāng)我們使用watch監(jiān)聽數(shù)據(jù)變化需要同時獲取新值和老值時,我們需要把數(shù)據(jù)源定義為函數(shù)的形式,并且把數(shù)據(jù)源進(jìn)行深拷貝返回。當(dāng)我們只需要新值時,可以增加deep:true選項即可。
- 其實(shí),引用類型的數(shù)據(jù)定義為ref形式也沒關(guān)系,也只需要把數(shù)據(jù)源定義為函數(shù)的形式,并且把數(shù)據(jù)源進(jìn)行深拷貝返回,便可獲得新老值~哈哈哈哈哈哈哈哈哈哈哈哈哈哈,但我覺得最佳實(shí)踐還是要把引用類型定義為reactive響應(yīng)式數(shù)據(jù)。
到此這篇關(guān)于詳解Vue3中Watch監(jiān)聽事件的使用的文章就介紹到這了,更多相關(guān)Vue3 Watch監(jiān)聽事件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
富文本編輯器quill.js?開發(fā)之自定義插件示例詳解
這篇文章主要為大家介紹了富文本編輯器quill.js?開發(fā)之自定義插件示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08vue-electron項目創(chuàng)建記錄及問題小結(jié)解決方案
這篇文章主要介紹了vue-electron項目創(chuàng)建記錄及注意事項,本文給大家分享了運(yùn)行項目報錯的問題小結(jié)及多種解決方案,需要的朋友可以參考下2024-03-03vue router學(xué)習(xí)之動態(tài)路由和嵌套路由詳解
本篇文章主要介紹了vue router 動態(tài)路由和嵌套路由,詳細(xì)的介紹了動態(tài)路由和嵌套路由的使用方法,有興趣的可以了解一下2017-09-09vue如何根據(jù)網(wǎng)站路由判斷頁面主題色詳解
這篇文章主要給大家介紹了關(guān)于vue如何根據(jù)網(wǎng)站路由判斷頁面主題色的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11