如何避免输入框聚焦重复加载XHR站点数据 实现一次初始化多字段复用
解决方案
核心实现逻辑是在内存中缓存已请求的站点数据,同时新增请求状态和待初始化队列,避免重复发起网络请求,具体优化代码如下:
优化 suggestion.js 文件
export default { // 缓存站点数据,请求成功后永久存储在内存中 cachedStations: null, // 请求状态标记,避免重复发起相同请求 isLoading: false, // 待初始化输入框队列,处理请求过程中多次触发聚焦的场景 pendingInputs: [], url: 'http://localhost:8090/api.php', getData() { this.isLoading = true fetch(this.url) .then(res => res.json()) .then(data => { this.cachedStations = data // 批量初始化队列中所有待绑定的输入框 this.pendingInputs.forEach(inputEl => { this.autocomplete(inputEl, data) }) this.pendingInputs = [] }) .catch(err => { console.log(err) }) .finally(() => { this.isLoading = false }); }, autocomplete(inp, arr) { // 原有自动完成逻辑无需修改 }, start(selector) { const inputEl = document.getElementById(selector) // 已初始化过的输入框跳过重复处理,无需该逻辑可删除此判断 if (inputEl.hasAttribute('data-autocomplete-init')) return // 已有缓存数据直接初始化当前输入框 if (this.cachedStations) { this.autocomplete(inputEl, this.cachedStations) inputEl.setAttribute('data-autocomplete-init', 'true') return } // 无缓存时加入待处理队列 this.pendingInputs.push(inputEl) inputEl.setAttribute('data-autocomplete-init', 'true') // 没有正在进行的请求时发起数据请求 if (!this.isLoading) { this.getData() } } }
app.js 和 html 代码无需修改
原有交互逻辑可直接复用,优化后第一次触发输入框聚焦时仅会发起1次站点数据请求,两个输入框都会绑定自动完成能力,后续聚焦不会再重复请求数据。
如果想要进一步提升交互响应速度,可以在app.js导入suggestion后直接调用suggestion.getData()预加载数据,用户第一次点击输入框时数据已经加载完成,无需等待网络请求。
内容的提问来源于stack exchange,提问作者Maik Lowrey
相关产品推荐
相关产品推荐

