本文共 2051 字,大约阅读时间需要 6 分钟。
Axios 是一个基于 Promise 的网络请求库,支持浏览器和 Node.js。它可以像普通的 HTTP 请求一样使用,适用于前端和后端开发。
get 请求主要用于获取数据,支持通过 URL 参数或请求体传递参数。
// 第一种写法axios.get('http://localhost:8080/static/data.json?id=1', { params: { id: 1 }}).then((res) => { console.log('数据:', res);});// 第二种写法axios({ method: 'get', url: 'http://localhost:8080/static/data.json', params: { id: 1 }}).then((res) => { console.log('数据:', res);}); post 请求用于提交数据,常用于表单提交或文件上传。
// 第一种写法axios.post('http://localhost:8080/static/data.json', data).then((res) => { console.log('数据:', res);});// 第二种写法axios({ method: 'post', url: 'http://localhost:8080/static/data.json', data: data}).then((res) => { console.log('数据:', res);}); patch 请求用于部分更新数据,适用于数据量较大的情况。
axios({ method: 'patch', url: 'http://localhost:8080/static/data.json', data: { name: 'updated name' }}).then((res) => { console.log('数据:', res);}); put 请求用于完全更新数据,适用于数据量较少的场景。
axios({ method: 'put', url: 'http://localhost:8080/static/data.json', data: { name: 'updated name' }}).then((res) => { console.log('数据:', res);}); 在项目中导入 Axios 库,确保其在 Vue 实例中使用。
import axios from 'axios';
以下是一个简单的 Vue 实例,用于展示 Axios 的使用场景。
var app = new Vue({ el: '#app', data: { tableData: [] }}); 在 Vue 实例中绑定一个方法,通过 Axios 发送请求并处理响应。
methods: { initTable() { axios.get('UsersServlet', { params: { method: 'index' } }).then(function (result) { app.tableData = result.data.data; }); }} 以下是一个使用 post 请求提交数据的示例。
axios.post('UsersServlet?method=insert', qs.stringify(this.addform)) .then(function (result) { if (result.data.code === 200) { that.$message.success(result.data.msg); that.initTable(); // 重新加载表格 that.dialogVisible = false; } }); 通过以上步骤,用户可以轻松地使用 Axios 进行各种网络请求,适用于前端和后端开发场景。
转载地址:http://kbhfk.baihongyu.com/