请求评论数据的方法,无法在created生命周期中调用。
来源:8-11 评论列表 - 获取评论列表数据

ForCoke
2022-03-17
1、在blog-detail页面中:
/**
* 通过小程序的页面加载事件,获取其他页面跳转过来传递的作者名和文章id
*/
onLoad(options) {
this.author = options.author;
this.articleId = options.articleId;
// 获取传递的参数后,立即发请求获取详情信息
this.getArticleDetail();
},
<!-- 评论组件 -->
<view class="comment-box">
<article-comment-list :articleId="articleId" :author="author"/>
</view>
2、在article-comment-list组件中:
created() {
console.log(this.articleId+"1111");
console.log(this.author);
this.getArticelCommentList();
},
问题:在created生命周期函数中:无法获取blog-detail组件中通过props函数传递过来的参数,两者都是空值,同时接口函数报错,articleId||page为必传项。
而我尝试了一下在调用接口的方法放入mounted生命周期函数中:
mounted() {
console.log(this.articleId+"1111");
console.log(this.author);
this.getArticelCommentList();
},
此时就能够正常获取到传递过来的参数,并且正常请求接口,获取响应,请问一下老师,这是怎么一回事?
写回答
1回答
-
你好
你的 articleId 是通过 this.getArticleDetail(); 这个方法获取的吗?
如果是的话,那么获取服务端数据是异步的操作,而create 中的打印是同步的,
所以有可能在《打印时还没有获取到数据,从而导致打印是 null》,
你可以给 article-comment-list 增加一个 v-if,等待数据获取成功之后再渲染组件,就像下面这样:
<article-comment-list v-if="articleId" :articleId="articleId" :author="author"/>
022023-04-24
相似问题