Vue使用v-for遍历数组给子组件传props仅生成单个模板问题
修复方案
核心问题:接口数据赋值错误
你请求返回的JSON结构外层包裹了posts字段,当前你直接将解析后的完整对象赋值给了this.posts,导致this.posts并非预期的帖子数组,而是{posts: [帖子数组]}的对象。v-for遍历该对象时仅会识别到1个属性,因此只会生成1个Post模板。
修复方法:调整getAllPosts方法中的赋值逻辑,取出对象内的posts数组:
.then((result) => { const res = JSON.parse(result); this.posts = res.posts; console.log(this.posts); })
额外问题修复
子组件Prop使用不规范
你在子组件中将Prop赋值给本地data属性的写法存在问题:组件的data函数仅在初始化时执行一次,父组件异步请求完成后更新Prop,子组件的本地articleData不会同步更新。建议直接在模板中使用Prop,无需额外存储到本地data:
<template> <div> <article class="postWithImage"> <h4 class="postWithImage__h4">Kaerbran {{articledata.Post_Comment}}</h4> </article> </div> </template> <script> import ModalBoxActionArticle from '../components/modalBoxActionArticle' export default { name: 'ImageArticle', props : ['articledata'] } </script>
如果确实需要将Prop存储为本地可修改的变量,可通过watch监听Prop变化同步更新本地值,或使用计算属性实现。
v-for key优化
当前你使用索引index作为v-for的key,数组顺序变更时会产生不必要的重渲染,建议改为每个Post自带的唯一标识Post_ID:
<div v-for="post in posts" :key="post.Post_ID"> <ImageArticle :articledata="post" class="home__component"/> </div>
内容的提问来源于stack exchange,提问作者Kaerbran
相关产品推荐
相关产品推荐

