天天看點

vue 封裝axios請求(基礎版)

建立頁面,封裝axios請求;

import axios from "axios";

//建立axios執行個體
var service = axios.create({
  baseURL: "後端接口位址字首",
  timeout: 5000,
  withCredentials: true,
  headers: {
    "content-type": "application/json",
  },
});
export default {
  service,

  //get請求
  get(url, data) {
    return service({
      url: url,
      method: "get",
      query: data,
    });
  },

  //post請求
  post(url, data) {
    return service({
      url: url,
      method: "post",
      data: data,
    });
  },
};      

main.js引用封裝的請求;

import http from "@/api/http.js"; //axios執行個體化後引入取名http
Vue.prototype.$http = http; //放入全局      

頁面使用請求

this.$http.get("後端接口位址字首的拼接",{data: 1,array: []}).then((res) => {});