vue 封装delete body传参接口
时间: 2024-09-19 12:06:16 浏览: 92
在Vue.js中,封装HTTP请求通常使用axios库来简化操作。当你需要发送一个DELETE请求,并希望从URL中移除查询参数,因为DELETE请求不带查询参数,而是通常用于删除资源,你可以这样做:
首先,在Vue组件中安装axios如果还没有安装:
```bash
npm install axios
```
然后创建一个自定义的DELETE方法:
```javascript
import axios from 'axios';
export default {
methods: {
deleteResource(url, id) {
// 创建一个只包含id参数的URL,因为我们不需要body数据
const modifiedUrl = `${url}?_method=delete&_id=${id}`;
// 使用axios的delete方法发送请求
axios.delete(modifiedUrl)
.then(response => {
console.log('Delete successful:', response.data);
// 这里处理成功回调逻辑
})
.catch(error => {
console.error('Delete error:', error.response.data);
// 这里处理错误回调逻辑
});
}
}
}
```
在这个例子中,`_method`和`_id`是隐藏字段,用于指定HTTP方法为DELETE,而真正的id作为参数传递。这遵循了一些API对DELETE请求的约定。
阅读全文
相关推荐

















