Vue SPA模态框切换图片时评论未更新问题求助
问题原因与解决方案
核心问题
评论组件comments-component仅在首次挂载(mounted钩子)时获取一次评论数据,当通过模态框切换图片导致imgId props更新时,组件没有触发新的评论请求,因此始终显示旧图片的评论。而关闭模态框重新打开时,组件会重新挂载,mounted钩子再次执行,所以能获取正确评论。
解决方案
有两种常用修复方式,任选其一即可:
方案1:监听imgId变化,重新获取评论
修改comments-component.js,将获取评论的逻辑抽成独立方法,并添加watch监听imgId变化,触发新的评论请求:
const commentsComponent = { data() { return { comments: [], username: "", comment: "", }; }, props: ["imgId"], mounted() { this.fetchComments(); }, watch: { imgId: function(newId) { this.fetchComments(newId); } }, methods: { fetchComments(imgId = this.imgId) { fetch(`/comments/${imgId}`) .then((res) => res.json()) .then((fetchedData) => { console.log("FETCHED DATA: comments are retreived", fetchedData); this.comments = fetchedData; }) .catch((err) => { console.log("ERROR: PROBLEM TO FETCH DATA ", err); }); }, handleCommentSubmit(e) { e.preventDefault(); fetch("/comment", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ comment: this.comment, username: this.username, image_id: this.imgId, }), }) .then((res) => res.json()) .then((data) => { this.comments.unshift(data.payload); this.username = ""; this.comment = ""; }) .catch((err) => { console.log("Error fetch comments: ", err); }); }, }, template: ` <div class="comments_component_div"> <div class="comments_form_div"> <form class="comments_form"> <input class="username_input" v-model='username' type="text" name="username" placeholder="User Name"> <textarea class="comment_input" v-model='comment' id="commentbox" type="text" name="comment" placeholder="Add Your Comment..." cols="30" rows="10"></textarea> <button class="comments_button" @click="handleCommentSubmit">Add Comment</button> </form> </div> <div class="single_comment_box" v-if="comments.length" v-for="comment in comments" :key="comment.id"> <div class="list_item"> <p id="username_par">{{comment.username}}:</p> <p id="comment_par">{{comment.comment}}</p> </div> </div> </div>` }; export default commentsComponent;
方案2:通过key强制组件重新挂载
修改modal-component.js中的comments-component标签,添加:key="selectedImg",这样当selectedImg变化时,Vue会销毁旧组件并创建新实例,自动触发mounted钩子获取新评论:
<comments-component v-bind:img-id="selectedImg" :key="selectedImg"></comments-component>
额外排查点(非必现,但建议验证)
- 浏览器缓存:如果后端接口未设置缓存控制头,浏览器可能缓存旧请求。可以在
fetch中添加cache: 'no-cache'强制刷新:fetch(`/comments/${this.imgId}`, { cache: 'no-cache' }) - 后端接口:在浏览器控制台的Network面板中,查看切换图片时
/comments/:imgId请求的响应内容,确认后端是否返回了对应图片的正确评论数据。
内容的提问来源于stack exchange,提问作者Asaf Nimer
相关产品推荐
相关产品推荐

