我有一个表格,可以添加新项目和编辑现有项目(每个条目旁边都有编辑按钮)。我有一个问题,如果您要添加一个新项目,而不刷新页面,然后去编辑该项目,它将在Vue上对其进行编辑,但不会将其传递回数据库。当您去编辑项目时,PUT URL返回404错误。但是,如果您在添加项目后刷新页面,则可以对其进行完美编辑。有什么想法我做错了,或者可能忘记添加了吗?删除方法也一样。
<script>
export default {
data: () => ({
dialog: false,
headers: [
{
text: 'Question',
align: 'left',
sortable: true,
value: 'question',
width: '25%'
},
{ text: 'Answer', value: 'answer', width: '55%' },
{ text: 'Actions', value: 'action', sortable: false, width: '20%' },
],
questions: [],
editedIndex: -1,
editedItem: {
question: '',
answer: ''
},
defaultItem: {
question: '',
answer: ''
},
}),
computed: {
formTitle () {
return this.editedIndex === -1 ? 'New Item' : 'Edit Item'
},
},
watch: {
dialog (val) {
val || this.close()
},
},
created () {
this.initialize();
this.loadUsers();
},
methods: {
initialize () {
this.questions = []
},
loadUsers(){
if (axios == null) {
return;
}
axios.get('/api/faq').then(res=>{
if(res.status === 200){
this.questions=res.data;
}
}).catch(err=>{
console.log(err);
});
},
editItem (item) {
this.editedIndex = this.questions.indexOf(item);
this.editedItem = Object.assign({}, item);
this.dialog = true
},
deleteItem (item) {
const index = this.questions.indexOf(item);
confirm('Are you sure you want to delete this item?') &&
axios.destroy('/api/faq/' + this.questions[this.editedIndex].id).then(response =>{
this.questions.splice(index, 1);
}).catch(error=>{
console.log('Deleting error')
})
},
close () {
this.dialog = false;
setTimeout(() => {
this.editedItem = Object.assign({}, this.defaultItem);
this.editedIndex = -1
}, 300)
},
saveToServer () {
if (this.editedIndex > -1) {
// Edit item
Object.assign(this.questions[this.editedIndex], this.editedItem);
axios.put('/api/faq/' + this.questions[this.editedIndex].id, this.editedItem).then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
} else {
//New item
this.questions.push(this.editedItem);
axios.post('/api/faq', this.editedItem).then(function (response) {
console.log('Before');
this.id = response.id;
console.log('After');
Object.assign(this.questions[this.editedIndex], this);
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
this.close()
},
},
}
</script>
存储控制器:
public function store(Request $request)
{
$id = faq::insertGetId($request->all());
return Response:: json([
'status' => 'ok',
'id' => $id,
], 200);
}
更新控制器:
public function update(Request $request, $id)
{
faq::findOrFail($id)->update($request->all());
return response(['message' => 'Success']);
}