vue输入节流,避免实时请求接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010394015/article/details/82116529

在做搜索的时候,当搜索页面只有一个输入框、没有确定按钮的时候,只能在用户输入时请求服务端,查询数据。这样会导致频繁的发送请求,造成服务端压力。解决这个问题,可以使用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>

猜你喜欢

转载自blog.csdn.net/u010394015/article/details/82116529