在 Vue 中正确使用 防抖 和 节流
生活随笔
收集整理的這篇文章主要介紹了
在 Vue 中正确使用 防抖 和 节流
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 觀察者防抖
1. 在 create() 鉤子 里,創建 防抖回調,并將其賦值到實例上:this.debouncedWatch = debounce(…, 500)。
2. 在 觀察者 回調 watch.value() { … } 中 傳入正確的參數 調用 this.debouncedWatch()。
3. 最后,beforeUnmount() 鉤子中 調用 this.debouncedWatch.cancel() ,在卸載組件之前,取消所有還在 pending 的 防抖函數執行。
<template><input v-model="value" type="text" /><p>{{ value }}</p> </template> <script> import _ from "lodash"; export default {data() {return {value: "",};},watch: {value(...args) {this.debouncedWatch(...args);},},created() {this.debouncedWatch = _.debounce((newValue, oldValue) => {console.log('New value:', newValue);}, 500);},beforeUnmount() {this.debouncedWatch.cancel();}, }; </script>2. 事件處理器 防抖
1. 在 create() 鉤子 里,創建實例后,立刻將 防抖回調 debounce(event => {…}, 500) 賦值到 this.debouncedHandler 。
2. 在輸入框的 template 中 給 v-on:input 賦上 debouncedHandler :
3. 最后,在卸載組件之前, 在 beforeUnmount() 鉤子中 調用 this.debouncedHandler.cancel() ,取消所有還在 pending 的 函數調用。
<template><input v-on:input="debouncedHandler" type="text" /> </template> <script> import _ from "lodash"; export default {created() {this.debouncedHandler = _.debounce(event => {console.log('New value:', event.target.value);}, 500);},beforeUnmount() {this.debouncedHandler.cancel();} }; </script>參考: https://juejin.cn/post/7034458741990752287
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的在 Vue 中正确使用 防抖 和 节流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 箭头函数特殊性与普通函数的区别
- 下一篇: 详细记录如何在跨域请求中携带cookie