# 搜索页

# 技术点

StorageSync triggerEvent debounce 函数使用 wx.request 取消请求

# 目录结构

└─ pages                          
   └─ search                      # 搜索页
      ├─ components               # 组件
      │  ├─ search-bar            # 搜索栏
      │  ├─ search-history        # 历史记录
      │  └─ search-result         # 搜索结果
      └─ index                    # 搜索入口页

# 介绍

用户输入需要查询的内容时,组件监听 bindinput 事件,对输入内容进行查询,查询接口调用前,会先 debounce 以待用户输入完成后再触发请求。如果请求结果未返回时,再次触发接口请求,则取消上次请求。

# wx.request 取消请求

由于用户在持续输入内容时,会多次触发查询接口,可能上一个接口数据未返回时,下一个接口已经返回数据,再上一个接口返回数据时,将当前查询的内容给覆盖掉,导致查询数据是错的;所以当触发查询请求时,需要将上次未返回的请求取消掉。

data: {
	cancel: null, // 请求实例
},

methods: {
	async search() {
		if (this.data.cancel) {
			this.data.cancel.abort();
			this.data.cancel = null;
		}

		this.data.cancel = wx.request({
			url: app.HOST + '/search',
			data: {},
			header: {
				'content-type': 'application/json',
				Authorization: 'Bearer ' + wx.getStorageSync('token')
			},
			success: ({code}) => {
				
			},
			fail: (err) => {
				
			},
			complete: () => {
				this.data.cancel = null
			}
		})
	}
}
上次更新: 2022-10-25 9:05:36 ├F10: PM┤