Vue+Vuex项目JavaScript自动补全功能优化及问题解决咨询
优化方案
一、修复无需刷新即可使用搜索的问题
核心根因
- Vuex
state.games初始值为字符串"",不是数组,首次执行过滤逻辑时会因调用数组方法filter报错,数据拉取后没有监听逻辑触发重新计算 - 直接修改Vuex state值,未严格遵循mutation修改规则,容易出现状态不同步
- 自动补全逻辑仅单次执行,未监听
games和输入关键词gameInput的变化
修复代码
- 修正Vuex state初始值
state: { games: [], // 改为空数组,匹配返回的列表结构 },
- 修正mounted中的请求逻辑,移除直接修改state的冗余代码,增加本地缓存读取逻辑
mounted() { // 优先读取本地缓存,实现秒开可用 const localGames = localStorage.getItem('gamesCache') if (localGames) { this.$store.dispatch('GetGames', JSON.parse(localGames)) } // 异步请求最新数据 axios.get('http://127.0.0.1:3000/games/all') .then(res=>{ this.$store.dispatch('GetGames', res.data); // 更新本地缓存 localStorage.setItem('gamesCache', JSON.stringify(res.data)) }) .catch(err=>console.log(err)) }
- 自动补全逻辑改为计算属性,利用Vue响应式自动更新结果,无需手动操作DOM
computed: { ...mapState(['games']), // 自动补全结果,会随games或gameInput变化自动更新 autocompleteList() { if (!this.gameInput.trim()) return [] const inputLow = this.gameInput.toLowerCase() // 用includes替代正则匹配,性能更高 return this.games.filter(item => item.gamename.toLowerCase().includes(inputLow)) }, // 自动控制补全框显隐 isAutocompleteDisabled() { return this.autocompleteList.length === 0 } }
模板中直接绑定autocompleteList和isAutocompleteDisabled即可,数据拉取后自动更新,无需刷新页面。
二、优化接口请求4s延迟问题
核心根因
200~300条数据查询耗时4s属于异常情况,大概率是未加数据库索引、未做接口缓存导致。
优化方案
- 给数据库
Game表的常用查询字段(如gamename)加索引,降低全表查询耗时 - 后端接口增加服务端内存缓存,游戏列表属于低频率更新数据,无需每次请求查库:
// 全局缓存变量,可根据更新频率设置过期时间 let gameListCache = null router.get('/all',(req,res,next)=>{ if (gameListCache) return res.json(gameListCache) Game.find({},(err,rows)=>{ if(err) throw err; const result = rows.length ? rows : [] gameListCache = result res.json(result); }); })
优化后接口请求耗时可降到100ms以内,配合前端localStorage缓存,二次打开页面时无需请求接口即可直接使用搜索功能。
三、可选体验优化
- 输入加防抖:设置300ms防抖,用户停止输入后再计算补全结果,减少不必要的计算开销
- 预构建索引:提前将所有游戏名转成小写存储,过滤时无需重复转小写,进一步提升过滤性能
内容的提问来源于stack exchange,提问作者권동규
相关产品推荐
相关产品推荐

