Vue.js字谜游戏Bug:选择任意长度均默认加载5字母词
解决Vue.js Anagram Hunt应用中单词长度不生效的问题
问题根源
从控制台日志可明确定位:
mounted钩子已成功获取到路由参数Word Length: 8- 但
newWord方法里打印的Word Length: 5,说明组件的wordLength数据始终沿用初始值5,未更新为用户选择的长度。
解决方案
需要将路由传递的单词长度参数同步到组件数据中,同时处理路由参数变化的场景:
在
mounted中同步路由参数
路由参数默认是字符串类型,需转为数字后赋值给this.wordLength,再调用newWord加载对应长度的单词。监听路由参数变化
若用户切换单词长度或从其他页面跳转进来,需监听$route.params.wordLength的变化,及时更新wordLength并重新加载单词。
修改后的代码片段
更新mounted钩子
mounted() { // 将路由参数转为数字并同步到组件数据 this.wordLength = Number(this.$route.params.wordLength); console.log('Selected Word Length:', this.wordLength); this.newWord(); this.startTimer(); }
添加watch监听路由参数
watch: { '$route.params.wordLength'(newLength) { this.wordLength = Number(newLength); this.newWord(); // 重新加载对应长度的单词组 } }
优化newWord方法(可选)
可直接使用this.wordLength,无需重复定义变量:
newWord() { console.log('Using Word Length:', this.wordLength); const wordArrays = anagrams[this.wordLength]; console.log('Word Arrays:', wordArrays); // 后续逻辑保持不变... }
验证效果
修改后,控制台会打印用户选择的单词长度,newWord方法将从anagrams对象中取出对应长度的单词数组,不再默认使用5字母单词。
内容的提问来源于stack exchange,提问作者Timothy Test Sr
相关产品推荐
相关产品推荐

