vue的watch監(jiān)聽器取消的方法小結
1. 使用 this.$watch 創(chuàng)建的監(jiān)聽器
如果你是通過 this.$watch
動態(tài)創(chuàng)建的監(jiān)聽器,this.$watch
會返回一個取消監(jiān)聽的函數,調用該函數即可取消監(jiān)聽
export default { data() { return { count: 0, }; }, created() { // 動態(tài)創(chuàng)建監(jiān)聽器 const unwatch = this.$watch( 'count', // 監(jiān)聽的屬性 (newVal, oldVal) => { console.log('count changed:', newVal); } ); // 取消監(jiān)聽 unwatch(); // 調用返回的函數即可取消監(jiān)聽 }, };
2. 在 watch 選項中定義的監(jiān)聽器
如果你是在組件的 watch
選項中定義的監(jiān)聽器,Vue 會在組件銷毀時自動取消這些監(jiān)聽器,因此通常不需要手動取消。
如果你需要手動取消監(jiān)聽器,可以通過以下方式實現:
方法 1:使用 this.$watch 替代 watch 選項
將 watch
選項中的監(jiān)聽器改為在 created
或 mounted
鉤子中使用 this.$watch
,然后保存返回的取消函數。
export default { data() { return { count: 0, }; }, created() { this.unwatchCount = this.$watch( 'count', (newVal, oldVal) => { console.log('count changed:', newVal); } ); }, methods: { stopWatching() { if (this.unwatchCount) { this.unwatchCount(); // 手動取消監(jiān)聽 } }, }, beforeDestroy() { this.stopWatching(); // 在組件銷毀前取消監(jiān)聽 }, };
方法 2:通過條件控制監(jiān)聽器的執(zhí)行
如果不想完全取消監(jiān)聽器,可以通過一個標志變量來控制監(jiān)聽器的執(zhí)行。
export default { data() { return { count: 0, isWatching: true, // 控制監(jiān)聽器的標志 }; }, watch: { count(newVal, oldVal) { if (this.isWatching) { console.log('count changed:', newVal); } }, }, methods: { stopWatching() { this.isWatching = false; // 停止監(jiān)聽 }, }, };
3. 使用 Vue 3 的 watch 函數
在 Vue 3 中,watch
是一個獨立的函數,調用后會返回一個取消監(jiān)聽的函數。
import { ref, watch } from 'vue'; export default { setup() { const count = ref(0); // 創(chuàng)建監(jiān)聽器 const stopWatch = watch(count, (newVal, oldVal) => { console.log('count changed:', newVal); }); // 取消監(jiān)聽 stopWatch(); return { count, }; }, };
總結
- 動態(tài)創(chuàng)建的監(jiān)聽器(通過
this.$watch
或 Vue 3 的watch
函數):可以通過調用返回的取消函數來取消監(jiān)聽。 watch
選項中定義的監(jiān)聽器:Vue 會在組件銷毀時自動取消,如果需要手動取消,可以改用this.$watch
或通過條件控制監(jiān)聽器的執(zhí)行。- Vue 3 的
watch
函數:直接調用返回的取消函數即可。
到此這篇關于vue的watch監(jiān)聽器取消的方法小結的文章就介紹到這了,更多相關vue watch監(jiān)聽器取消內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue表單驗證rules及validator驗證器的使用方法實例
在vue開發(fā)中,難免遇到各種表單校驗,下面這篇文章主要給大家介紹了關于vue表單驗證rules及validator驗證器使用的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2022-07-07Vue echarts 實現離線中國地圖的示例代碼(細化到省份)
這篇文章主要介紹了Vue echarts 實現離線中國地圖,細化到省份,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-09-09Vue遞歸組件+Vuex開發(fā)樹形組件Tree--遞歸組件的簡單實現
這篇文章也是我自己開發(fā)的從無到有的過程,所以它可以為你提供一些Tree組件開發(fā)的思路,本文重點給大家介紹vue遞歸組件的簡單實現,感興趣的朋友跟隨小編一起看看吧2019-04-04vue項目動態(tài)設置頁面title及是否緩存頁面的問題
這篇文章主要介紹了vue項目動態(tài)設置頁面title及是否緩存頁面的問題,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11