我有一个问题,我的 axios.delete 方法删除了数组中的错误对象。总共有 3 个对象,来自 api,当我在 index.html 文件中删除时,id 为 2 和 3 的对象很好,但它抛出“未捕获(承诺)错误:请求失败,状态代码 404”错误我尝试删除来自我的 API 的数组中的第一个对象。
我的索引文件(包括删除按钮)
<body>
<div id="app">
<template v-for="(results, index) in result">
<div class="card" style="width: 20rem; display:inline-block;">
<div class="card-block">
<p>{{ results }}</p>
<button type="button" class="btn btn-danger pull-right" data-toggle="modal" v-on:submit.prevent="deleteData(index)" @click="deleteData(results, index) in result">Delete</button>
<h1> {{ results.comments}} </h1>
</div>
</div>
</template>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue"></script>
<script src="src/main.js"></script>
主.js
var vm = new Vue ({
el: '#app',
data: {
result: ''
},
created: function(){
this.getResult();
},
methods: {
deleteData: function(result, id) {
axios.delete('https://my-json-server.typicode.com/json/posts/' + id)
.then(response => {
this.result.splice(id, 1)
console.log(this.result);
});
},
getResult: function() {
// this.results = 'Loading...';
axios.get('https://my-json-server.typicode.com/json/db')
.then(response => {
// console.log(response.data);
this.result = response.data.posts;
console.log(this.result);
});
}
}
});
原文由 themanwiththemasterplan 发布,翻译遵循 CC BY-SA 4.0 许可协议
如我所见,您将两个参数传递给
deleteData
方法。第二个参数是结果数组的索引,它不是您的真实结果 ID。在这里,你只需要用这个替换你的
deleteData
方法:正如您在上面看到的,我们刚刚将您的
id
更改为result.id