欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在Vue中使用防抖與節(jié)流,及this指向的問題

 更新時間:2022年01月23日 15:15:20   作者:IMP_L  
這篇文章主要介紹了在Vue中使用防抖與節(jié)流,及this指向的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

使用防抖與節(jié)流,及this指向問題

最近項目中遇到了防抖與節(jié)流問題,搜索了很多文章都有this指向的問題,最后不得不采取一種很low的方法

data中定義isFirst為1

if (this.isFirst < 2){
? ? this.isFirst = 2
? ? setTimeout(() => {
? ? ? ? this.isFirst = 1
? ? ? }, 1000)
? }

這樣就形成了假的節(jié)流

但是我們怎么能屈服于這種寫法

繼續(xù)探索vue項目中用閉包的方式防抖節(jié)流

一頓操作后

?const delay = (function () {
? ? let timeout
? ? return (callback, ms) => {
? ? ? if (timeout) clearTimeout(timeout)
? ? ? let callNow = !timeout
? ? ? timeout = setTimeout(() => {
? ? ? ? timeout = undefined
? ? ? }, ms)
? ? ? if (callNow) callback.apply(this, [callback, ms])
? ? }
? })()
?export default {
?? ?methods: {
?? ??? ?delay(() => {
? ? ? ? ? // do something
? ? ? ?}, 1000)
?? ?}
}

用了立即執(zhí)行的函數(shù)方法,就能夠獲取到全局的this了 

使用防抖函數(shù)所遇見的坑

以前的防抖和節(jié)流都是在js中直接書寫,后使用vue進行組件化開發(fā)之后,有些地方需要注意。

正常寫法

? ? function debounce(func, delay) {
? ? ? let timeout
? ? ? return function () {
? ? ? ? let context = this;
? ? ? ? let args = arguments;
? ? ? ? if (timeout) {
? ? ? ? ? clearTimeout(timeout)
? ? ? ? }
? ? ? ? timeout = setTimeout(() => {
? ? ? ? ? func.apply(context, args)
? ? ? ? }, delay)
? ? ? }
? ? }

使用

? ? function change(volume, data) {
? ? ? debounce(() => {
? ? ? ? console.log('change', volume, data);
? ? ? }, 500)
? ? }

Vue中寫法使用

注意: Vue中使用時,需要定義timeout,同時在防抖函數(shù)中,this的指向發(fā)生了變化,需要在return之前獲取vue實例。這個時候,你直接使用,還是不行的,只要debug就會發(fā)現(xiàn)debounce返回的func沒有進去,需要手動執(zhí)行一下(添加括號)。

? data() {
? ? return {
? ? ? timeout: null
? ? }
? }
? ? change(volume, data) {
? ? ? this.debounce(() => {
? ? ? ? console.log('change', volume, data)
? ? ? }, 500)
? ? },
? ? debounce(func, delay) {
? ? ? let context = this // this指向發(fā)生變化,需要提出來
? ? ? let args = arguments
? ? ? return function () {
? ? ? ? if (context.timeout) {
? ? ? ? ? clearTimeout(context.timeout)
? ? ? ? }
? ? ? ? context.timeout = setTimeout(() => {
? ? ? ? ? func.apply(context, args)
? ? ? ? }, delay)
? ? ? }()// 注意:我加了()
? ? }

Vue中的watch的防抖簡寫

? ? watchObj: {
? ? ? handler(val) {
? ? ? ? let _this = this
? ? ? ? clearTimeout(this.timeout)
? ? ? ? this.timeout = setTimeout(() => {
? ? ? ? ? _this.handlerData(val)
? ? ? ? }, 500)
? ? ? }
? ? }

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論