安装配置axios

3 篇文章 0 订阅
本文详细介绍了如何在TypeScript和Vue3项目中安装并配置axios,包括全局设置请求和响应拦截器,以及在组件中发送请求的实战示例。
摘要由CSDN通过智能技术生成

这是一个TypeScript+vue3的实战项目,完成创建vue项目后,接下来安装配置axios。

一、axios是干什么的

简单来说,Axios 是一个 HTTP 客户端库,可以用来在浏览器和 Node.js 中发送 HTTP 请求,处理数据等。

二、安装

npm install axios

三、全局配置

在src目录下,创建一个axios目录管理axios配置文件,在axios目录下创建axiosConfig.ts,内容如下:

import axios from "axios";

//创建一个axios实例对象
const http = axios.create({

});

//设置请求拦截器(回调函数)
http.interceptors.request.use((req)=>{
    return req;
})

//设置响应拦截器
http.interceptors.response.use((res)=>{
    return res;
})

//把http实例对象暴露出去
export default http;

四、挂载到项目上

将http对象挂载到app上

import axios from './axios/axiosConfig';
//将axios挂载到app这个实例上
app.config.globalProperties.$http=axios;

五、发送一个axios请求验证一下

在src文件夹下,创建一个test文件夹用于测试,添加test.vue文件,内容如下:

<template>
    <div>
    </div>
</template>
<script lang="ts">
import {defineComponent, getCurrentInstance} from 'vue';
export default defineComponent({
    name:'myTest',
    setup(){
        const {proxy}: any = getCurrentInstance();
        //发送axios请求
        function ajaxTest(){
            proxy.$http.get('https://images.pexels.com/photos/2014422/pexels-photo-2014422.jpeg')
            .then((res: any)=>{
                console.log(res);
            })
            .catch((error: any)=>{
                console.log(error);
            });
        }
        //发送请求,直接调用
        ajaxTest();
    }
})
</script>
<style scoped>
</style>

再将上面的代码引入项目中,在HomeView.vue文件中,引入、注册、使用。这是修改后的HomeView.vue:

<template>
  <div class="home">
    <!-- <img alt="Vue logo" src="../assets/logo.png"> 
    <HelloWorld msg="Welcome to Your Vue.js + TypeScript App"/>-->
  </div>
  <my-test></my-test>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import myTest from '../test/test.vue'

export default defineComponent({
  name: 'HomeView',
  components: {
    myTest,
  },
  props: {
    msg: String,
  }
});
</script>

六、运行结果

在这里插入图片描述
还可以刷新试试:
在这里插入图片描述
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/03f467d6a7374dbb9735fe78e8019c6d.png

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值