vue輸入節(jié)流,避免實時請求接口的實例代碼
在做搜索的時候,當搜索頁面只有一個輸入框、沒有確定按鈕的時候,只能在用戶輸入時請求服務端,查詢數(shù)據(jù)。這樣會導致頻繁的發(fā)送請求,造成服務端壓力。
解決這個問題,可以使用vue做輸入節(jié)流。
1、創(chuàng)建一個工具類,debounce.js
/*** * @param func 輸入完成的回調(diào)函數(shù) * @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é)流,避免實時請求接口的實例代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue?Echarts實現(xiàn)實時大屏動態(tài)數(shù)據(jù)顯示
同大多數(shù)的前端框架一樣,先讀官網(wǎng)的使用方法。學會基本使用后,在實例中找到自己想要demo。拿過來改一改,一個echarts圖表就形成,畢竟人家做就是為了方便使用,這篇文章主要介紹了Vue?Echarts實現(xiàn)實時大屏動態(tài)數(shù)據(jù)顯示2022-10-10vue3實現(xiàn)無縫滾動列表效果(大屏數(shù)據(jù)輪播場景)
vue3-scroll-seamless 是一個用于 Vue 3 的插件,用于實現(xiàn)無縫滾動的組件,它可以讓內(nèi)容在水平或垂直方向上無縫滾動,適用于展示輪播圖、新聞滾動、圖片展示等場景,本文就給大家介紹了vue3實現(xiàn)無縫滾動列表效果,需要的朋友可以參考下2024-07-07Vue-router不允許導航到當前位置(/path)錯誤原因以及修復方式
本文主要介紹了Vue-router不允許導航到當前位置(/path)錯誤原因以及修復方式,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09vue項目中做編輯功能傳遞數(shù)據(jù)時遇到問題的解決方法
這篇文章主要介紹了vue項目中做編輯功能傳遞數(shù)據(jù)時遇到問題的解決方法,vue父組件向子組件傳遞數(shù)據(jù)的問題,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12