Vue3 如何使用 axios
在 Vue 3 中集成和使用 Axios
Axios 是一个流行的 JavaScript 库,用于在浏览器和 Node.js 中进行 HTTP 请求。它提供了简洁的 API,可以轻松地发送异步请求并处理响应数据。在 Vue 3 中,我们可以使用 Axios 来与后端进行数据交互。
参考资料:Axios 官方文档:Getting Started | Axios Docs
示例,在 Vue 3 中 使用 Axios 进行数据请求。通过集成 Axios 发送异步请求,并处理响应数据
一、安装 Axios:首先,在你的 Vue 3 项目中安装 Axios。打开终端,进入你的项目根目录,然后运行以下命令:
安装 Axios 库及其依赖。
npm install axios

二、在需要使用 Axios 的组件中,通过 import 关键字引入 Axios:
import axios from 'axios';

三、发送了 GET 请求到 /api/data 接口,并通过 then 方法处理成功响应,通过 catch 方法处理请求错误。
axios.get('/api/data')
.then(response => {
// 处理响应数据
})
.catch(error => {
// 处理请求错误
});
四、发送了 POST 请求到 /api/data 接口,并传递了一个数据对象
axios.post('/api/data', { data: 'example' })
.then(response => {
// 处理响应数据
})
.catch(error => {
// 处理请求错误
});
五、Vue3 配置 Axios 为全局对象
main.js
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
//createApp(App).mount('#app')
const app = createApp(App)
app.config.globalProperties.$axios = axios
app.mount('#app')

调用方式一
//axios请求 ------------------------------------------------- var params=new URLSearchParams(); params.append('login',"admin"); params.append('password',"admin"); this.$axios.post('/sina/api/sessions', params) .then(response => { // 处理响应数据 console.log(response.data); this.current_call_token= response.data; }) .catch(error => { // 处理请求错误 console.log(error); }); //--------------------------------------------------------------
调用方式二
var params=new URLSearchParams(); params.append('login',"admin"); params.append('password',"admin"); this.$axios.post('/sina/api/sessions', params) .then(function (response) { console.log(response); console.log(response.data); this.current_call_token= response.data.token; console.log(this.current_call_token); }.bind(this)) .catch(function (error) { console.log(error); });
感谢 「一直在学习的小白~」 https://blog.csdn.net/m0_61998604/article/details/131135554

浙公网安备 33010602011771号