Vue3使用axios


一直用UNIAPP,這次項目要用vue來寫,就比較糾結
裝了vue3,然后挺多不適應的,記錄下接口使用吧

安裝

$ npm install axios --save

創建config.js

這里創建攔截器跟配置域名

import axios from 'axios';
import { ElMessageBox } from 'element-plus';

const config = {
  // baseURL: process.env.baseURL
  baseURL: 'https://www.baidu.com/api',
  timeout: 1000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
};

const api = axios.create(config);

// 默認 post 請求,使用 application/json 形式
api.defaults.headers.post['Content-Type'] = 'application/json';


//封裝下post
api.post = function(url,params){
      return new Promise((resolve, reject) => {
        // console.log("****************************");
        axios({
          method: 'post',
          url:config.baseURL + url,
          params,
          headers: {
            'Content-Type': 'application/json; charset=utf-8',
          },
        }).then(response => {
          if (response.status == 200) {
            //根據實際情況進行更改
            resolve(response)
          } else {
            reject(response)
          }
        })
      })

}

// http response 攔截器
api.interceptors.response.use(
  response => {
    //攔截響應,做統一處理
    if (response.data.code) {
      // console.log(response.status);
      switch (response.status) {
        case 301:
          console.log('登錄過期');
          // store.state.isLogin = false
          // router.replace({
          //   path: 'login',
          //   query: {
          //     redirect: router.currentRoute.fullPath
          //   }
          // })
      }
    }
    return response
  },
  //接口錯誤狀態處理,也就是說無響應時的處理
  error => {
    return Promise.reject(error.response.status) // 返回接口返回的錯誤信息
  })

export default api;

main.js中引用

vue3沒有vue2里的vue.prototype,用的這種方式

import api from './assets/config/config';
const app = createApp(App);
app.config.globalProperties.$api = api;

使用

vue3需要在setup中使用proxy來
https://vue3js.cn/docs/zh/api/composition-api.html#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90

  import {
   onMounted, onUpdated, onUnmounted,
   getCurrentInstance,
} from 'vue';
  setup() {
    const { proxy } = getCurrentInstance();
    console.log('proxy', proxy);
    console.log(proxy.$http);
    proxy.$api.post('/API/URL/GETLIST', {
      params: {

      },
    }).then((res) => {
      console.log(res);
    }).catch((err) => {
      console.log(err);
    });
    return { //必須返回 模板中才能使用
      proxy
    }
  },

在方法調用時

   getList() {
      this.proxy.$api.post('/API/URL/GETLIST', {
        params: {

        },
      }).then((res) => {
        console.log(res);
      }).catch((err) => {
        console.log(err);
      });

      this.$router.push({
        name: 'Project-list',
      });
    },


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM