vue3 axios使用配置

vue3 axios使用配置

安装axios 和 qs

cnpm install axios -S

cnpm install qs  -S

在项目中创建axios.js(尾汁根据自己喜好而定)

axios.js

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

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

//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 => {
     
  	alert(`异常请求:${
       JSON.stringify(error.message)}`)
  }
);
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)
        })
    })
  }
};

main.js中全局引用axios

import axios from './static/js/axios';
const app = createApp(App);
//全局配置
app.config.globalProperties.$http=axios;

可以在组件用通过 getCurrentInstance() 来获取全局 globalProperties 中配置的信息,getCurrentInstance 方法获取当前组件的实例,然后通过 ctx 属性获得当前上下文,这样我们就能在 setup 中使用 axios来请求数据

如何调用,举个栗子

<script>
import {
     
  computed,
  defineComponent,
  getCurrentInstance,
  onMounted,
  reactive,
  ref,
  toRefs,
} from "vue";
export default defineComponent({
     
  name: "demo",
  props: "",
  components: "",
  setup(props, context) {
     
    //引用全局变量
    const {
      ctx } = getCurrentInstance();
    let state = reactive({
     
      buttonName: "点击发送请求",
    });
    //dom挂载后
    onMounted(() => {
     
      sendHttp();
    });

    function sendHttp() {
     
      ctx.$http
        .post("/test", {
     
          id: 1,
          name: "test",
        })
        .then((res) => {
     
          //请求成功
        })
    }
    return {
     
      ...toRefs(state),
      sendHttp,
    };
  },
});
</script>

vite+vue3+axios+element-plus集成

你可能感兴趣的:(vue3,vue.js)