vue3引入axios

  1.下载axios

1
npm install axios --save

  2.在scr目录下自定义一个 reques t文件夹  

  3.在刚刚建的文件夹中创建一个引入axios的api.js文件

  4.api.js里引入

1
import axios from 'axios'

  5.设置默认前缀以及请求时间传参类型拦截器等等.....

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import axios from 'axios'
import { ElMessage } from 'element-plus'  //这个是引入的Element 3.0的提示消息
 
const service = axios.create({
    baseURL: 'http://........', // 自己项目中请求地址前缀部分
    timeout: 60000, // 请求超时时间毫秒
    withCredentials: true, // 异步请求携带cookie
    headers: {
        // 设置后端需要的传参类型
        'Content-Type': 'application/json',
        'token': 'your token',
        'X-Requested-With': 'XMLHttpRequest',
    },
})
 
// 添加请求拦截器
service.interceptors.request.use(
    function (config) {
        // 在发送请求之前做些什么
        return config
    },
    function (error) {
        // 对请求错误做些什么
        console.log('出错了',error)
        return Promise.reject(error)
    }
)
 
// 添加响应拦截器
service.interceptors.response.use(
    function (response) {
        console.log('响应了',response)
        
        // 这个地方响应了数据该做点什么 做想做的事情
        // dataAxios 是 axios 返回数据中的 data
        const dataAxios = response.data
        // 这个状态码是和后端约定的
        // const code = dataAxios.reset
        return dataAxios
    },
    function (error) {
        
        // 对响应错误做点什么
        console.log('出错了',error)
        ElMessage({
            message: '接口报错了',
            type: 'success',
          })
        return Promise.reject(error)
    }
)
export default service   //最后暴露出去

  6.在src目录下新建一个统一储存接口的地方 比如创建一个文件夹apis  文件夹下可以分模块来放置对应的请求的接口  然后引入刚刚设置的axios

1
2
3
4
5
6
7
8
9
10
import httpRequest from '../request/api'
 
// 获取用户信息
export function userLogin(param) {
    return httpRequest({
        url: '/posts'//自己请求的接口
        method: 'get'//请求方式
        data: param,    //参数
    })
}

  7.在项目中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script setup>
 
import { onMounted } from 'vue'
 
import { userLogin } from '@/apis/login' //这里引入的就是刚刚添加的接口
 
function getUserInfo() {
     const param = {rows:10,page:1}  //自己组装参数
     userLogin(param).then((res) => {
         console.log(res)
     })
}
/**
  相当于Vue2的mounted生命周期
 *vue3没有created 和beforeCreated了
 *
 */
onMounted(() => {
  console.log('222')
     getUserInfo()
})
</script>

  

 

 

 
posted @   热爱前端的5号机器  阅读(1972)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示