在做搜索的时候,当搜索页面只有一个输入框、没有确定按钮的时候,只能在用户输入时请求服务端,查询数据。这样会导致频繁的发送请求,造成服务端压力。
解决这个问题,可以使用vue做输入节流。
1、创建一个工具类,debounce.js
/*** * @param func 输入完成的回调函数 * @param delay 延迟时间 */ export function debounce(func, delay) { let timer return (...args) => { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { func.apply(this, args) }, delay) } }
2、在搜索页面使用
<template>
<div class="xn-container">
<input type="text" class="text-input" v-model="search">
</div>
</template>
<script>
import {debounce} from '../utils/debounce'
export default {
name: 'HelloWorld',
data () {
return {
search: ''
}
},
created() {
this.$watch('search', debounce((newQuery) => {
// newQuery为输入的值
console.log(newQuery)
}, 200))
}
}
</script>
<!-- Add "scoped" attribute to limit css to this component only -->
<style scoped>
.text-input {
display: block;
width: 100%;
height: 44px;
border: 1px solid #d5d8df;
}
</style>
以上这篇vue输入节流,避免实时请求接口的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持前端开发者。
» 本文来自:前端开发者 » 《Vue输入节流,避免实时请求接口的实例代码_气质_前端开发者》
» 本文链接地址:https://www.rokub.com/71130.html
» 您也可以订阅本站:https://www.rokub.com
评论前必须登录!
注册