vue3使用axios 封装使用

首先先下载

npm install axios --save
npm install qs --save

在项目中创建axios.js

import axios from "axios";
import qs from "qs";

// axios.defaults.baseURL = ''  //正式
axios.defaults.baseURL = 'http://localhost:3000' //测试

//post请求头
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
//允许跨域携带cookie信息
axios.defaults.withCredentials = true; 
//设置超时
axios.defaults.timeout = 15000;

axios.interceptors.request.use(
    config => {
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

axios.interceptors.response.use(
    response => {
        if (response.status == 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    },
    error => {

        alert(JSON.stringify(error), '请求异常', {
            confirmButtonText: '确定',
            callback: (action) => {
                console.log(action)
            }
        });
    }
);
export default {
    /**
     * @param {String} url 
     * @param {Object} data 
     * @returns Promise
     */
    post(url, data) {
        return new Promise((resolve, reject) => {
            axios({
                    method: 'post',
                    url,
                    data: qs.stringify(data),
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                });
        })
    },

    get(url, data) {
        return new Promise((resolve, reject) => {
            axios({
                    method: 'get',
                    url,
                    params: data,
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                })
        })
    }
};

在main.js中

import axios from './util/axios';
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App);
app.use(store)
   .use(router)
   .mount('#app')
app.config.globalProperties.$axios = axios;

在组件中直接使用

 import {useStore} from 'vuex'
import { ref, reactive, getCurrentInstance, onMounted, defineComponent } from "vue"
export default defineComponent ({
  name: 'Home',
  setup( props, context) {
    const homeStore = new useStore(); //使用useStore 实例化store
    const { proxy } = getCurrentInstance(); //来获取全局 globalProperties 中配置的信息
    //dom挂载后
    onMounted(() => {
      sendHttp();
    });

    //发送验证码 get同理
    const sendHttp = () => {
      proxy.$axios
        .post("/captcha/sent", {
          phone: 12345678912,
        })
        .then((res) => {
          //请求成功
          console.log(res)
        })
        .catch( err => {
          console.log(err)
        })
    
    }
    return {
      sendHttp
    }
  }
})

封装api使用

import axios from "../util/axios";
let {get, post } = axios
//发送验证码
export const sendCaptcha = data => get("/captcha/sent",data)

//验证验证码
export const verifyCaptcha = data => post("/captcha/verify",data)

//注册(修改密码)
export const register = data => post("/register/cellphone",data)

在组建中调用api

import { ref,getCurrentInstance} from "vue"
import { sendCaptcha} from "../api/login"
export default {
    setup() {
        const captcha = ref('') //验证码
        const phone =ref('')// 手机号码
        const {proxy} = getCurrentInstance() //获取全局配置信息
        const onSubmit = () => {
            proxy.$axios
                .post("/captcha/sent", {
                    phone: 18700880154,
                })
                .then((res) => {
                //请求成功
                console.log(res)
                })
                .catch( err => {
                console.log(err)
                })
            };
    
        return {
            captcha,
            phone,
            onSubmit
        }
    },
    methods:{
        sendCaptcha(){
            sendCaptcha({phone:this.phone}).then((res) =>{
                console.log(res)
            })
        }
    }
}
posted @ 2021-10-08 16:45  清风~~徐来  阅读(3483)  评论(0编辑  收藏  举报