vue3 使用axios
时间: 2023-07-22 17:52:43 浏览: 52
Vue3 中使用 axios 进行网络请求的方法与 Vue2 中基本相同,可以通过 npm 安装 axios:
```
npm install axios --save
```
然后在需要使用的地方引入 axios:
```javascript
import axios from 'axios'
```
接下来就可以使用 axios 进行 GET 或 POST 请求了。例如:
```javascript
axios.get('/api/users')
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})
axios.post('/api/users', {
name: 'John Doe',
email: 'john@example.com'
})
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})
```
需要注意的是,在 Vue3 中,应该将 axios 实例定义在一个单独的模块中,然后在需要使用的组件中引入使用,这样可以避免多个组件重复定义。例如:
```javascript
// api.js
import axios from 'axios'
const api = axios.create({
baseURL: 'http://localhost:3000',
timeout: 1000,
headers: { 'X-Custom-Header': 'foobar' }
})
export default api
```
```javascript
// MyComponent.vue
import api from './api.js'
export default {
methods: {
fetchData() {
api.get('/users')
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})
}
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)