uniapp实现防抖搜索

接口说明

根据文章标题(title)模糊搜索

  • 搜索接口:http://localhost:3000/search?keyword=xxx

组件准备

<template>
  <view id="wrapper">
    <!-- 搜索框区域 -->
    <view class="headBox">
      <view class="search">
        <i class="iconfont icon-search"></i>
        <input placeholder="请输入关键词" v-model="keyword" @input="handleSearch" />
      </view>
      <view class="searchBtn" @click="onCancel">
        取消
      </view>
    </view>
  </view>
</template>

搜索实现

<script>
	export default {
   
		data() {
   
			return {
   
				// 1、定义搜索参数
				keyword: ''
			}
		},
		methods: {
   
			// 2、触发 input 框执行搜素方法
			async handleSearch(e) {
   
				// 3、获取用户输入内容并设置给 keyword 属性
				this.keyword = e.target.value
				
				//4、请求搜索接口,带上搜索参数
				const {
   
					data: res
				} = await uni.$http.get(`/search?keyword=${
     this.keyword}`)
				console.log(res)
			}
		}
	}
</script>

img.png

用户的关键词还未输入完就已经多次请求了接口,显然是不合理的,要解决这个问题,需了解 js 的防抖概念

继续修改代码如下

<script>
	export default {
   
		data() {
   
			return {
   
				keyword: '',
				// 2、设置定时器
				timer: null,
                articles: []
			}
		},
		methods: {
   
			handleSearch(e) {
   
				this.keyword = e.target.value
				
				// 4、清除定时器
				clearTimeout(this.timer)
				
				// 3、使用定时器 setTimeout 延迟 500 毫秒去请求搜索接口
				this.timer = setTimeout(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值