防抖:触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。
节流:高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率
防抖
在src下 新建utils,新建common.js
/*debounce*/
export function debounce(fn, delay = 1000) {
let timer = null
return function () {
let args = arguments
if (timer) {
clearTimeout(timer)
timer = null
}
timer = setTimeout(() => {
fn.apply(this, args)// this 指向vue
}, delay)
}
}
使用
<el-row>
<el-col :span="12">
<div class="grid-content bg-purple">
<el-form inline>
<el-form-item>
<el-input v-model="message" placeholder="请输入内容"></el-input>
</el-form-item>
<el-form-item>
<el-button type="success" @click="search">搜索</el-button>
</el-form-item>
</el-form>
</div>
</el-col>
</el-row>
import { debounce } from '@/utils/common.js'
methods:{
search:debounce(function () {
console.log(this.message)
},500)
}
节流
在common.js
/*throttle*/
export function thorttle(fn, delay = 1000) {
let lastTime = ''
let timer = ''
let interval = delay
return function () {
let args = arguments
let nowTime = Date.now()
if (lastTime && nowTime - lastTime < interval) {
clearTimeout(timer)
timer = setTimeout(() => {
lastTime = nowTime
fn.apply(this, args)
}, interval)
} else {
lastTime = nowTime
fn.apply(this, args)
}
}
}
使用
<input type="text" v-model="messageInput" @keyup="search">
import { thorttle } from '@/utils/common.js'
methods:{
search:thorttle(function () {
console.log(this.messageInput)
},1000)
}
网友评论