接口说明
根据文章标题(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>
用户的关键词还未输入完就已经多次请求了接口,显然是不合理的,要解决这个问题,需了解
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(