vue輸入節(jié)流,避免實時請求接口的實例代碼
更新時間:2019年10月30日 14:40:00 作者:、不知不覺、
今天小編就為大家分享一篇vue輸入節(jié)流,避免實時請求接口的實例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
在做搜索的時候,當搜索頁面只有一個輸入框、沒有確定按鈕的時候,只能在用戶輸入時請求服務端,查詢數據。這樣會導致頻繁的發(fā)送請求,造成服務端壓力。
解決這個問題,可以使用vue做輸入節(jié)流。
1、創(chuàng)建一個工具類,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輸入節(jié)流,避免實時請求接口的實例代碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue-router不允許導航到當前位置(/path)錯誤原因以及修復方式
本文主要介紹了Vue-router不允許導航到當前位置(/path)錯誤原因以及修復方式,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09