【发布时间】:2017-01-24 13:38:02
【问题描述】:
我正在尝试学习使用 Laravel 构建的 API 的 Vue.js。这个想法很简单,一个用户可以发一个帖子,一个帖子可以有 cmets。我可以让关系在 laravel 中工作,但我不知道如何使用 Vue.js 返回帖子的作者姓名或评论。
当使用刀片模板引擎时,我在 foreach 循环中使用类似的东西来返回作者姓名:
{{ $post->user->name }}
当我通过 API 返回帖子时,除了用户 ID 外,我没有获得任何用户信息。如何获取属于该帖子的用户信息?
{
"message": "Success",
"data": [
{
"id": 1,
"body": "test body 1",
"user_id": "1",
"created_at": "2016-09-16 10:22:57",
"updated_at": "2016-09-16 10:22:57"
}
]
}
<script>
export default {
/*
* The component's data.
*/
data() {
return {
posts: [],
};
},
/**
* Prepare the component.
*/
ready() {
this.getPosts();
},
methods: {
/**
* Get Posts.
*/
getPosts: function() {
this.$http.get('/api/wall/posts')
.then(response => {
this.posts = response.data.posts;
});
}
}
}
</script>
public function getPosts($id = null)
{
if (!$id){
$data = Post::all();
$message = 'Success';
$code = 200;
} else {
$data = Post::FindOrFail($id);
$message = 'Success';
$code = 200;
}
return Response::json(['message' => $message, 'data' => $data], $code);
}
【问题讨论】: