Vue3页面刷新时请求已触发但组件未加载问题
问题分析与解决方案
问题描述
开发了一个Vue应用,代码如下:
<template> <div class="text-center"> <table class="table"> <thead> <tr> <th scope="col">پاسخ</th> <th scope="col">سؤال</th> <th scope="col">شماره سؤال</th> </tr> </thead> <tbody> <tr v-for="question in this.questions" :key="question.id-1"> <th scope="row"> <input class="form-check-input" type="checkbox" /> </th> <td>{{question.question_text}}</td> <td>{{question.id-1}}</td> </tr> </tbody> </table> <button type="submit" class="btn btn-primary m-5" @click="handlsubmit">ثبت پاسخ</button> </div> </template> <script> export default { name: "InitialTest", data() { return { questions: this.$store.state.diagnosis.question }; }, beforeCreate() { this.$store.dispatch("diagnosis/insertQuestion"); } } </script>
首次加载时应用运行正常,但刷新页面后,尽管请求已被触发,组件却无法正常加载。
问题原因
刷新页面时组件的初始化流程存在异步时序问题:
beforeCreate钩子触发异步dispatch请求获取数据- 紧接着执行
data初始化,此时store中的diagnosis.question还未被异步请求更新,questions被赋值为空或初始默认值 - 后续异步请求完成、
store状态更新时,data里的questions不会自动同步——它只是初始赋值的普通变量,不具备响应式关联store状态的能力
首次加载正常是因为之前的会话中store已缓存数据,data初始化时能拿到已有值。
解决方案
把data里的questions替换为计算属性,让它自动响应store状态变化:
修改后的代码:
<template> <div class="text-center"> <table class="table"> <thead> <tr> <th scope="col">پاسخ</th> <th scope="col">سؤال</th> <th scope="col">شماره سؤال</th> </tr> </thead> <tbody> <tr v-for="question in questions" :key="question.id-1"> <th scope="row"> <input class="form-check-input" type="checkbox" /> </th> <td>{{question.question_text}}</td> <td>{{question.id-1}}</td> </tr> </tbody> </table> <button type="submit" class="btn btn-primary m-5" @click="handlsubmit">ثبت پاسخ</button> </div> </template> <script> export default { name: "InitialTest", beforeCreate() { this.$store.dispatch("diagnosis/insertQuestion"); }, computed: { questions() { // 返回store状态,状态更新时计算属性自动重新计算 return this.$store.state.diagnosis.question || []; } } } </script>
额外优化点
- 模板中访问组件属性无需加
this,直接写questions即可 - 计算属性里加
|| [],确保store状态为空时返回空数组,避免v-for遍历undefined报错
内容的提问来源于stack exchange,提问作者Nana99
相关产品推荐
相关产品推荐

