tft每日頭條

 > 生活

 > vuewatch使用教程交流

vuewatch使用教程交流

生活 更新时间:2025-01-18 16:55:53

vuewatch使用教程交流?<script> import { toRef,toRefs,watch } from "vue"; export default { props: [title], setup(props) { const state = reactive({ listParam: { searchKey: "", mainFollower: "" } }) const t1 = watch(() => state.listParam.searchKey, (newVal,oldVal) => { console.log(newVal, oldVal) state.listParam.searchKey = newVal.trim() setTimeout(() => { t1();// 取消監聽 }, 5000) }) watch([() => state.listParam.customerName, () => state.listParam.mainFollower], ([newCustomerName, newMainFoller],[oldCustomerName,oldMainFoller]) => { state.listParam.customerName = newCustomerName.trim() state.listParam.mainFollower = newMainFoller.trim() },{ immediate: true }) const t2 = watchEffect(() => { state.listParam.searchKey = state.listParam.searchKey ? state.listParam.searchKey.trim() : "" state.listParam.mainFollower= state.listParam.mainFollower? state.listParam.mainFollower.trim() : "" setTimeout(() => { t2();// 取消監聽 }, 5000) }) return { state } }, }; </script> Copy ,今天小編就來聊一聊關于vuewatch使用教程交流?接下來我們就一起去研究一下吧!

vuewatch使用教程交流(vue3.0總結之watch與watchEffect)1

vuewatch使用教程交流

watch監聽單一或多個數據 watch也可以變為非惰性的 立即執行的 添加第三個參數 immediate: truewatchEffect監聽數據,可以單個或多個,不需要傳入監聽的數據源,而是直接執行裡面的方法,獲取到更新後的值。兩個方式都返回監聽實例 通過調用自身可取消監聽

<script> import { toRef,toRefs,watch } from "vue"; export default { props: [title], setup(props) { const state = reactive({ listParam: { searchKey: "", mainFollower: "" } }) const t1 = watch(() => state.listParam.searchKey, (newVal,oldVal) => { console.log(newVal, oldVal) state.listParam.searchKey = newVal.trim() setTimeout(() => { t1();// 取消監聽 }, 5000) }) watch([() => state.listParam.customerName, () => state.listParam.mainFollower], ([newCustomerName, newMainFoller],[oldCustomerName,oldMainFoller]) => { state.listParam.customerName = newCustomerName.trim() state.listParam.mainFollower = newMainFoller.trim() },{ immediate: true }) const t2 = watchEffect(() => { state.listParam.searchKey = state.listParam.searchKey ? state.listParam.searchKey.trim() : "" state.listParam.mainFollower= state.listParam.mainFollower? state.listParam.mainFollower.trim() : "" setTimeout(() => { t2();// 取消監聽 }, 5000) }) return { state } }, }; </script> Copy

總結watchEffect 不需要指定監聽的屬性,他會自動的收集依賴,隻要在回調函數中引用到了響應式的屬性,那麼當這些屬性變動的時候,這個回調都會執行,而 watch 隻能監聽指定的屬性而作出變動(v3開始能夠同時指定多個)。watch 能夠獲取到新值與舊值(更新前的值),而 watchEffect 是拿不到的。watchEffect 在組件初始化的時候就會執行一次用以收集依賴,收集到的依賴發生變化時再執行。而 watch 則是直接指定依賴項。,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关生活资讯推荐

热门生活资讯推荐

网友关注

Copyright 2023-2025 - www.tftnews.com All Rights Reserved