Vue中mounted钩子调用axios获取数据失败该如何解决?
问题根因
你的getThemes是异步方法,即使内部使用了async/await封装,在mounted中直接调用时,JS不会等待接口请求返回就会立刻执行后面的this.filteredThemes = this.themes和console.log代码,此时接口还没返回数据,this.themes还是初始值,所以打印结果不符合预期。
可行解决方案
方案1:mounted钩子添加异步等待逻辑
直接给mounted也加上async修饰,调用getThemes时添加await关键字,保证接口请求完成后再执行后续逻辑:
async mounted() { // 等待异步请求完成再执行后续赋值、打印操作 await this.getThemes(); this.filteredThemes = this.themes; console.log(this.themes); },
方案2:监听themes变化自动同步filteredThemes
如果后续themes可能会多次更新(比如有重新拉取数据、筛选的需求),可以用watch监听themes的变化,自动更新filteredThemes,无需耦合在请求逻辑里:
// 新增watch配置 watch: { themes: { immediate: true, // 初始赋值时也触发一次 handler(newVal) { this.filteredThemes = newVal; console.log(newVal); } } }, mounted() { this.getThemes(); },
代码优化建议
- 建议
getThemes中不要混用async/await和then链式调用,写法可以更统一:
async getThemes() { const response = await axios.get("url"); this.themes = response.data; },
- 初始化data时给
themes和filteredThemes设置默认空数组,同时模板中访问深层属性时添加可选链判断,避免渲染报错:
<theme-card v-for="theme in filteredThemes" :router-link="`/theme/${theme.slug}`" :key="theme.id" :name="theme.name" :tags="theme.tags" :id="theme.id" :path="theme.image?.path" <!-- 可选链避免image为空时报错 --> ></theme-card>
内容的提问来源于stack exchange,提问作者blackrox
相关产品推荐
相关产品推荐

