vue3.0脚手架 配置axios

vue3.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文件夹建一个可以存放配置文件,具体命名按照规范来即可
在这里插入图片描述
3、建立完成后config.js文件我用来存放后端请求接口地址,http.js封装axios的请求方式,index.js用来所有调用接口的方法
3.1 config,js文件,可以配置不同环境对应的地址

export default {
    
    
    baseUrl: {
    
    
      dev: "http://xxxx.xx.xx/", // 开发环境
      // 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,post } from "@/api/http";
export const getData = (params) => get("后端接口名",params);
export const getData1 = (data) => post("后端接口名",data);
//此处如果有参数传入给后端就需要写上参数 params/data 否则可以为空
export const getData = () => get("后端接口名");
export const getData1 = () => post("后端接口名");

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

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

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

猜你喜欢

转载自blog.csdn.net/weixin_44255044/article/details/114373564