海边的小溪鱼

vuePress-theme-reco 海边的小溪鱼    2017 - 2023
海边的小溪鱼 海边的小溪鱼

Choose mode

  • dark
  • auto
  • light
首页
分类
  • CSS
  • HTTP
  • Axios
  • jQuery
  • NodeJS
  • JavaScript
  • Vue2
  • Server
  • Vue3
标签
时间轴
更多
  • Gitee (opens new window)
Getee (opens new window)
author-avatar

海边的小溪鱼

28

文章

14

标签

首页
分类
  • CSS
  • HTTP
  • Axios
  • jQuery
  • NodeJS
  • JavaScript
  • Vue2
  • Server
  • Vue3
标签
时间轴
更多
  • Gitee (opens new window)
Getee (opens new window)

Axios 在 Vue 中的使用

vuePress-theme-reco 海边的小溪鱼    2017 - 2023

Axios 在 Vue 中的使用

海边的小溪鱼 2022-07-14 Vue2Axios

如何在 Vue 中使用 Axios 发起请求

# 1. axios 私有用法

// 1. 项目下安装axios
npm install axios -S

// 2. 组件中 导入 axios
import axios from "axios"

// 3. 组件中 使用 axios 发起请求
async getInfo() {
    const { data: res } = await axios.get('Api接口全地址') // 请求方式 get 或 post 等
    console.log(res)
}
1
2
3
4
5
6
7
8
9
10
11

# 2. axios 全局用法

// 1. 项目下安装axios
npm install axios -S

// 2. main.js 入口文件中 导入并全局配置 axios
import axios from "axios"
axios.defaults.baseURL = "API接口根地址"
Vue.prototype.$http = axios // 给 axios 命名为 $http

// 3. 组件中 使用 axios 发起请求
async getInfo() {
    const { data: res } = await this.$http.get('/user/list') // 请求方式 get 或 post 等
    console.log(res)
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 3. axios 更酷的用法

1. 安装 axios

npm install axios -S
1

2. 新建 src/utils/request.js 文件,并导入 axios

import axios from 'axios'

// 创建axios实例
const instance = axios.create({ baseURL: 'http://121.4.184.254:1234/api/v1' }) // 请求根路径

// 请求拦截器
instance.interceptors.request.use(
    (config) => config,
    (err) => Promise.reject(err)
);

// 响应拦截器
instance.interceptors.response.use(
    (response) => response,
    (err) => Promise.resolve(err.response)
);

export default instance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

3. 新建 src/api/video.js 文件(视频相关的接口模块),并封装一系列请求数据的方法

import request from "@/utils/request.js"

// 视频列表(get 请求)
export function getListApi(data) {
    return request.get("/video/list", data);
}

// 热门视频(post 请求)
export function HotListApi(data) {
    return request.post("/video/list", data);
}
1
2
3
4
5
6
7
8
9
10
11

4. 组件中按需导入并使用

<script>
import { getListApi, HotListApi } from "@/api/video.js";
export default {
    methods: {
        // 发起请求(不携带参数)
        async videoList() {
            const { data: res } = await getListApi();
            console.log(res);
        },
        // 发起 get 请求(携带参数)
        async getList() {
            const { data: res } = await getListApi({
              params: { order: 1, limit: 5 }
            });
            console.log(res);
        },
        // 发起 post 请求(携带参数)
        async postList() {
            const { data: res } = await HotListApi({ order: 2, limit: 18 });
            console.log(res);
        }
    }
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 4. axios 正确的使用方法(终极)

1. 安装 axios

npm install axios -S
1

2. 新建 src/http/http.js 文件,并导入 axios

import axios from 'axios'

// 创建axios实例
const instance = axios.create({ baseURL: 'http://121.4.184.254:1234/api/v1' }) // 请求根路径

// 请求拦截器
instance.interceptors.request.use((response) => {
    // 在发送请求之前做些什么
    return response;
}, (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(
    // 请求成功
    (res) => {
        if (res.status === 200) {
            return Promise.resolve(res.data)
        } else {
            return Promise.reject(res)
        }
    },
    // 请求失败
    (error) => {
        return Promise.reject(error)
    })

export default instance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

3. 新建 src/api/video.js 文件(视频相关的接口模块),并封装一系列请求数据的方法

import axios from '@/http/http.js'

const video = {
    // 视频列表
    list(data) {
        return axios.post('/video/list', data)
    },
    // 热门视频
    hotList(data) {
        return axios.post('/video/list', { ...data, order: 1, limit: 5 })
    },
}

export default video
1
2
3
4
5
6
7
8
9
10
11
12
13
14

4. 新建 src/http/index.js 文件(api统一处理模块),并引入视频相关的接口模块

import video from '@/api/video.js' // 视频相关的接口

export default {
    video
}
1
2
3
4
5

5. main.js 入口文件中引入 api 统一处理的模块

import http from './http'
Vue.prototype.$http = http // 绑定到vue原型中,组件中: this.$http -> axios
1
2

6. 在组件中发起请求

<script>
export default {
    methods: {
        // 请求视频列表数据
        getVideos() {
            this.$http.video.list({order: 1, limit: 5}).then(({ data }) => {
                console.log(data.list);
            })
        },
    },
    mounted() {
        this.getVideos()
    }
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

7. 如何在组件中同时发起多个请求

<script>
import axios from "axios"
    
export default {
    methods: {
        getData () {
            // 同时发起多个请求
            axios.all([
                this.$http.video.swiperVideo(), // 轮播
                this.$http.video.hotList(), // 热门视频
                this.$http.video.category(), // 分类
            ]).then(axios.spread((advert, hotVideo, category) => {
                this.swiperMovies = advert.data // 轮播
                this.hotMovies = hotVideo.data.list // 热门
                this.moreClassify = category.data // 分类
            })).catch(err => {
                console.log("请求失败", err);
            })
        },
    },
    mounted() {
        this.getData()
    }

};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# 5. 如何在请求时携带Token

// 1. 在登录组件中,登录成功时将 token 存储至本地或Vuex;在登录失败时清除 token

// 2. 在请求拦截器中携带 token
instance.interceptors.request.use((response) => {
    response.headers.Authorization = window.sessionStorage.getItem("token") // 在每次发起请求时都携带 token
    return response;
}, (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
})
1
2
3
4
5
6
7
8
9
10
帮助我们改善此页面! (opens new window)