我正在使用Laravel和Vue作为前端框架,对于ajax调用我正在使用axios,但只有在页面刷新时才加载数据。
路线:
路线::得到( '/注释', '@ CommentController显示'); 路线::交( '/存储', 'CommentController @商店');
Vue组件:
<template>
<div>
<form>
<div class="form-group">
<label>title</label>
<input v-model="comment.title" type="text" class="form-control">
</div>
<div class="form-group">
<label>body</label>
<textarea v-model="comment.body" class="form-control" placeholder="Add comment.."></textarea>
</div>
<button @click.prevent="add()" class="btn btn-primary">Comment</button>
</form>
</div>
</template>
<script>
export default {
data(){
return{
comment:{
title:"",
body:""
}
}
},
methods:{
add: function(){
axios.post('/store',{
title: this.comment.title,
body: this.comment.body
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
}
</script>
CommentController:
public function show(){
$comments= comment::orderby('id','desc')->get();
return $comments;
}
public function store(Request $request){
$this->validate($request,[
'title'=> 'required',
'body' => 'required'
]);
comment::create([
'title'=> request('title'),
'body' => request('body')
]);
return redirect('/');
}