如何实现Vue中输入节流功能,防止频繁调用接口?

更新于
2026-09-28 08:24:28
1阅读来源:SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计460个文字,预计阅读时间需要2分钟。

如何实现Vue中输入节流功能,防止频繁调用接口?

在搜索时,若页面仅有一个输入框且无确定按钮,用户输入后需手动请求服务端查询数据。这会导致频繁的发送请求,增加服务器压力。可采取以下措施解决:

1. 设置自动发送间隔,如用户输入后延迟一段时间再发送请求。

2.添加搜索按钮,用户点击后触发请求。

3.实现智能搜索,当用户输入一定数量的字符后自动发送请求。

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

解决这个问题,可以使用vue做输入节流。

1、创建一个工具类,debounce.js

如何实现Vue中输入节流功能,防止频繁调用接口?

/*** * @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输入节流,避免实时请求接口的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。

标签:实例

本文共计460个文字,预计阅读时间需要2分钟。

如何实现Vue中输入节流功能,防止频繁调用接口?

在搜索时,若页面仅有一个输入框且无确定按钮,用户输入后需手动请求服务端查询数据。这会导致频繁的发送请求,增加服务器压力。可采取以下措施解决:

1. 设置自动发送间隔,如用户输入后延迟一段时间再发送请求。

2.添加搜索按钮,用户点击后触发请求。

3.实现智能搜索,当用户输入一定数量的字符后自动发送请求。

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

解决这个问题,可以使用vue做输入节流。

1、创建一个工具类,debounce.js

如何实现Vue中输入节流功能,防止频繁调用接口?

/*** * @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输入节流,避免实时请求接口的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。

标签:实例