【发布时间】:2018-09-20 10:09:49
【问题描述】:
嗨朋友们,我正在使用 laravel 5.6 和 vue.js 来实现 crud 功能。我想获取我刚刚在帖子部分发布的帖子,而无需再次重新加载整个页面。我已经编写了这段代码,但是这些代码将数据发送到控制台而不是帖子视图部分。
我的 app.js 看起来像这样
const app = new Vue({
el: '#app',
data: {
msg: 'Update new Post:',
content:'',
posts:[]
},
ready:function(){
this.created();
},
created(){
axios.get('http://{mylink}/home/post')
.then(response=>{
console.log(response.data);//show if success
this.posts = response.data; // putting posts into array
})
.catch(function (error) {
console.log(error.response);
});
},
methods:{
addPost(){
axios.post('http://{mylink}/home/addPost', {
content:this.content
})
.then(function(response){
console.log('Data updated');
if (response.status == 200) {
alert('Your post has been updated');
app.posts=reponse.data;
}
})
.catch(function(error){
console.log(error.response);
});
}
}
});
我的控制器看起来像这样
public function posts(){
$posts=DB::table('posts')
->leftJoin('users','users.id','posts.user_id')
->leftJoin('profiles','profiles.user_id','posts.user_id')
->get();
return view('home',compact('posts'));
}
public function addPost(Request $request){
$content = $request->content;
$createPost=DB::table('posts')
->insert(['content'=>$content,'user_id'=>Auth::user()->id,
'status'=>0,'created_at'=>date("Y-m-d H:i:s"),'updated_at'=>date("Y-m-d H:i:s")]);
if($createPost){
$posts_json = DB::table('posts')
->leftJoin('users','users.id','posts.user_id')
->leftJoin('profiles','profiles.user_id','posts.user_id')
->orderBy('posts.created_at','DESC')->take(2)
->get();
return $posts_json;
}
}
路线看起来像这样
Route::post('/home/addPost','PostController@addPost')->name('home.addPost');
Route::get('/home/post',function(){
$posts_json = DB::table('posts')
->leftJoin('users','users.id','posts.user_id')
->leftJoin('profiles','profiles.user_id','posts.user_id')
->orderBy('posts.created_at','DESC')
->get();
return $posts_json;
});
我的观点是这样的
<div v-for="post in posts">
<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>@{{post.content}}</p>
<footer class="blockquote-footer">Status By <cite title="Source Title">@{{post.name}}</cite> <img src="{{url('/')}}/img/" alt="Card image cap" height="30px" width="30px" style="border-radius:50%;"></footer>
</blockquote>
</div>
</div>
</div>
【问题讨论】:
-
去掉ready函数,创建的会自己执行
-
另外我认为 {mylink} 不正确:axios.get('http://{mylink}/home/post')
-
您可以使用 VueJS 的 created() 或mounted() 生命周期钩子。您不需要为您的场景使用 ready 函数。
标签: javascript php laravel vue.js