Vue.js如何从API获取的数据中提取随机ID,代码运行无输出该如何解决?
问题修复方案
现有代码存在的问题
- 生命周期执行顺序错误:
created钩子早于mounted执行,此时还未调用接口请求方法,mostPlayed是空数组,无法取到随机值 - 异步逻辑时序错误:
getMostPlayed是异步请求,需要等待接口返回、mostPlayed赋值完成后,才能执行随机取值逻辑 - 随机方法不符合需求:现有
randomItem仅返回单个随机元素,你需要的是多个仅包含id字段的元素组成的数组 - 语法错误:
getMostPlayed方法的catch块末尾多了多余逗号,会导致代码运行报错
修复后完整代码
data() { return { mostPlayed: [], randomData: [], } }, methods: { async getMostPlayed() { try { const response = await axios.get(url); const data = response.data.slice(0, 9); this.mostPlayed = data; // 接口拿到数据后再生成随机id数组,这里指定生成3个,可按需修改 this.randomData = this.generateRandomIds(3, true); } catch (error) { console.log(error); } }, // 生成随机id数组,count为生成数量,unique为是否需要去重 generateRandomIds(count, unique = false) { const result = []; const usedIds = new Set(); const maxCount = unique ? this.mostPlayed.length : Infinity; // 数量超过数据源最大长度时取最大值 count = Math.min(count, maxCount); while(result.length < count) { const randomIndex = Math.floor(Math.random() * this.mostPlayed.length); const item = this.mostPlayed[randomIndex]; if(unique && usedIds.has(item.id)) continue; usedIds.add(item.id); result.push({ id: item.id }); } return result; } }, mounted() { this.getMostPlayed(); }
效果说明
调用generateRandomIds(3, true)后,randomData就会输出你期望的格式,比如:[ { id: 3 }, { id: 1 }, { id: 5 } ]
如果后续需要重新生成新的随机id数组,直接调用this.generateRandomIds方法传入对应参数即可。
内容的提问来源于stack exchange,提问作者Blek Wit
相关产品推荐
相关产品推荐

