vue3组合式 API:使用axios调接口方式

使用方式:新建request.js文件。

封装axios请求:
      注入请求拦截器:做请求前处理(参数加密,接口带token等等)。
      响应拦截器:(响应参数处理)

项目安装axios

npm install axios -S

代码实现
(注意util文件我就不复制了,将就看。。。。实在不懂看我给axios添加加密文章添加链接描述)
baseUrl 还是懂的吧

import axios from 'axios'
import util from "../Util"

axios.defaults.timeout = 50000
// 返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500 // 默认的
}
// 跨域请求,允许保存cookie
axios.defaults.withCredentials = true
// HTTPresponse拦截
axios.interceptors.response.use(res => {
  const status = Number(res.status)
  const message = res.data.msg || errorCode[status] || errorCode['default']
  if (status === 401) {
    logOut()
    return
  }
  if ((status !== 200 || res.data.code === 1) && res.config.url.indexOf("refresh_token") < 0) {
    Message({
      message: message,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  }
  return res
}, error => {
  return Promise.reject(new Error(error))
})

export default function request(config, data = {}) {
 
  const Public = data
  let httpDefaultOpts = resolveRes ? {
    method: config.method || 'POST',
    url: util.baseUrl + config.url,
    headers: {
      Authorization: config.needToken ? getToken('access_token') : 'Basic cGlnOnBpZw==',
      'TENANT-ID': '1',
      isToken: false,
    },
    responseType: "blob",
    data: Public
  } : {
    method: config.method || 'POST',
    url: util.baseUrl + config.url,
    headers: {
      Authorization: config.needToken ? getToken('access_token') : 'Basic cGlnOnBpZw==',
      'TENANT-ID': '1',
      isToken: false,
    },
    data: Public
  }
  // const loading = this.$loading({
  //   lock: true,
  //   text: "加载",
  //   spinner: "el-icon-loading",
  //   background: "rgba(0, 0, 0, 0.7)",
  // });
  return new Promise((resolve, reject) => {
    axios(httpDefaultOpts)
      .then(res => {
        // loading.close();
        if(res.data.sign){
          if (resolveRes) {
            resolve(res);
          } else if (res.code === 0) {
            resolve(res)
          } else {
            resolve(res.data)
          } 
        }else{
         console.log('不加密');
          if (resolveRes) {
            resolve(res);
          } else if (res.data.code === 0) {
            resolve(res.data)
          } else  {
            resolve(res.data)
          }
        }
      })
      .catch(err => {
        // loading.close();
        reject(err)
      })
  })

}

入口文件引入,

import request from "@/api/request";
const app = createApp(App);
app.config.globalProperties.$http = request;

使用vue3组合式 API

组件使用
import {roleList} from '@/api/api'
import {
  getCurrentInstance,
  defineComponent,
  onMounted,
  reactive,toRefs
} from "vue";
export default defineComponent({
  props: "",
  components: "",
  setup(props, context) {
    //引用全局变量
    const { proxy } = getCurrentInstance();//必须proxy,生产环境才有效
    let state = reactive({
      buttonName: "点击发送请求",
      name:''
    });
    //dom挂载后
    onMounted(() => {
      sendHttp();
    });
    function onclick(){
      state.name = 'ces'
    }
    // setInterval(()=>{
    //   state.name += '--'
    // }, 1000)
    function sendHttp() {
      proxy.$http(roleList,{type:1}).then(res =>{
        console.log(res)
      })
    }
    return {
      ...toRefs(state),
      sendHttp,
      onclick
    };
  },
});

你可能感兴趣的:(笔记,vue.js,前端,javascript)