vue 3.0 脚手架项目配置axios

1、首先安装axios ,vue-axios,使用yarn 或者npm 安装

使用yarn:
yarn add axios
yarn add vue-axios
使用npm
npm install axios
npm install vue-axios

2、安装完成后在项目src文件夹建一个可以存放配置文件,具体命名按照规范来即可

image.png

3、建立完成后config.js文件我用来存放后端请求接口地址,http.js封装axios的请求方式,index.js用来所有调用接口的方法

3.1 config,js文件,可以配置不同环境对应的地址

export default {
  baseUrl: {
    dev: "http://112.20.101.174:7070/", // 开发环境
    // fat: 'http://xxx.xx.xx.xx:8080' 
    //uat : "http://production.com" 
  },
};

3.2 http.js 封装axios超时请求时间,get请求、post请求,封装的目的是为了统一调用引入方法,不用在所有界面引入,具体代码如下

import axios from "axios"; // 引用axios
import config from "@/api/config";

const instance = axios.create({
  baseURL: config.baseUrl.dev,
  timeout: 60000,
});
//get请求
export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params: params,
      })
      .then((response) => {
        resolve(response);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
//post请求
export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    instance.post(url, data).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

3.3 index.js引入封装的get/post请求方法,直接调用后端接口地址

import { get } from "@/api/http";

export const getCompanyDetail = () => get("后端接口名");

4、最后在界面中调用index.js的方法就可以了

<template>
   
</template>
<script>
import { getCompanyDetail } from '@/api/index.js';
export default {
    name: '',
    mounted() {
        this.getCompany();
    },
     methods: {
        getCompany(){
            getCompanyDetail().then(res=> {
            })
            .catch(error=>{
                console.log(error)
            });
         },
    },
}
</script>

<style lang="less">
</style>

基本配置就完成了,可以正常调用接口

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容