vue输入节流,避免实时请求接口的实例代码

时间:2021-05-26

在做搜索的时候,当搜索页面只有一个输入框、没有确定按钮的时候,只能在用户输入时请求服务端,查询数据。这样会导致频繁的发送请求,造成服务端压力。

解决这个问题,可以使用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输入节流,避免实时请求接口的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章