Axios 在删除时向控制器发送 POSITION 而不是 ID
Axios sends POSITION instead of ID to the controller on delete
我是 vue js 的新手,我发现它的某些部分有点令人困惑,但这是我面临的最新困惑。
例如,我想删除id为3但它在列表中的位置为0的行,当点击删除它时returns控制台错误:
DELETE http://simvuecore/api/contoh/0 404 (Not Found)
这意味着 axios 发送 position
而控制器期望 id
即使 id
实际上没有在那里说明。
作为参考,这里是我的代码:
API routes
:
Route::delete('/contoh/{contoh}', 'contohController@destroy');
contohController
:
public function destroy(contoh $contoh)
{
$contoh->delete();
return response('terhapus', 200);
}
store.js
:
state: {
contoh: []
},
mutations: {
deleteContoh(state, id) {
const index = state.contoh.findIndex(item => item.id == id)
state.contoh.splice(index, 1)
}
},
actions: {
deleteContoh(context, id) {
axios.delete('api/contoh/' + id)
.then(response => {
context.commit('deleteContoh', id)
})
},
}
contohItem.vue
:
methods: {
removeContoh(id) {
this.$store.dispatch('deleteContoh', id)
},
所有 CRUD 操作在使用 POSTMAN
和从 vue 请求时都能正常工作,delete
是唯一不能工作的,因为 position
和 id
问题。
问题:
如何告诉 axios 将 id
而不是 position
发送到控制器?
更新:
按照@andrey popov 的回答解决了问题。
我在 contohItem.vue
:
<span @click="removeContoh(index)" class="remove-contoh">X</span>
我把它改成这样后就可以了:
<span @click="removeContoh(id)" class="remove-contoh">X</span>
从您的代码中我可以看到您一直在传递 id
函数,而 deleteContoh
操作实际上将其发送到服务器。这意味着你调用 removeContoh
的方式是问题 - 你传递的不是 id
而是 index
,因此你应该改变它。
祝你好运!
我是 vue js 的新手,我发现它的某些部分有点令人困惑,但这是我面临的最新困惑。
例如,我想删除id为3但它在列表中的位置为0的行,当点击删除它时returns控制台错误:
DELETE http://simvuecore/api/contoh/0 404 (Not Found)
这意味着 axios 发送 position
而控制器期望 id
即使 id
实际上没有在那里说明。
作为参考,这里是我的代码:
API routes
:
Route::delete('/contoh/{contoh}', 'contohController@destroy');
contohController
:
public function destroy(contoh $contoh)
{
$contoh->delete();
return response('terhapus', 200);
}
store.js
:
state: {
contoh: []
},
mutations: {
deleteContoh(state, id) {
const index = state.contoh.findIndex(item => item.id == id)
state.contoh.splice(index, 1)
}
},
actions: {
deleteContoh(context, id) {
axios.delete('api/contoh/' + id)
.then(response => {
context.commit('deleteContoh', id)
})
},
}
contohItem.vue
:
methods: {
removeContoh(id) {
this.$store.dispatch('deleteContoh', id)
},
所有 CRUD 操作在使用 POSTMAN
和从 vue 请求时都能正常工作,delete
是唯一不能工作的,因为 position
和 id
问题。
问题:
如何告诉 axios 将 id
而不是 position
发送到控制器?
更新:
按照@andrey popov 的回答解决了问题。
我在 contohItem.vue
:
<span @click="removeContoh(index)" class="remove-contoh">X</span>
我把它改成这样后就可以了:
<span @click="removeContoh(id)" class="remove-contoh">X</span>
从您的代码中我可以看到您一直在传递 id
函数,而 deleteContoh
操作实际上将其发送到服务器。这意味着你调用 removeContoh
的方式是问题 - 你传递的不是 id
而是 index
,因此你应该改变它。
祝你好运!