vue3如何实现挂载并使用axios

vue3挂载并使用axios

首先在main.js中引入axios并挂载到app.config.globalProperties上

axios配置文件放置./assets/js/axios

main.js

import {
    createApp
} from 'vue'
import App from './App.vue'
import './index.css'
import axios from './assets/js/axios';
const app = createApp(App);
app.use(router).use(ElementPlus).mount('#app')
app.config.globalProperties.$http = axios;

其次配置axios.js文件

axios.js

import axios from "axios";
import qs from "qs";
import {
    ElMessageBox
} from 'element-plus';
// axios.defaults.baseURL = ''  //正式
axios.defaults.baseURL = 'http://localhost:8089' //测试
//post请求头
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
//设置超时
axios.defaults.timeout = 10000;
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 => {
        ElMessageBox(JSON.stringify(error), '请求异常', {
            confirmButtonText: '确定',
            callback: action => {}
        });
    }
);
export default {
    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)
                })
        })
    }
};

最后在.vue中使用

通过getCurrentInstance拿到的ctx就有了$http可以调用

import {
  defineComponent,
  getCurrentInstance,
  reactive,
  toRefs,
} from "vue";
export default defineComponent({
  name: "demo",
  props: {},
  components: "",
  setup(props, context) {
    //引用全局变量
    const { ctx } = getCurrentInstance();
    console.log(ctx);
    let state = reactive({
      ruleForm: {
        username: "fur",
        password: "123",
      }
    });
    function submitForm() {
      ctx.$http.post("/login/xxx", ruleForm).then((res) => {
        //请求成功
      });
    }
    return {
      ...toRefs(state),
      submitForm,
    };
  },
});

vue3如何实现挂载并使用axios_第1张图片

vue全局挂载axios




  
  
  
  Document


  

vue3如何实现挂载并使用axios_第2张图片

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

你可能感兴趣的:(vue3如何实现挂载并使用axios)