1. 程式人生 > >vue axios 簡單封裝

vue axios 簡單封裝

先安裝 axios

npm install axios

vue axios 簡單封裝

下面是簡單的封裝一個 http.js, 在此說明 checkStatus 這個方法呢 是不一定需要的 ,根據個人的專案需求吧,也可以直接返回response,交給後面另行處理也行。

或者根據後端返回的狀態,在裡面進行處理 也行。

"use strict";
import axios from "axios";
import qs from "qs";
//新增請求攔截器
axios.interceptors.request.use(
 config => {
 return config;
 },
 error => {
 return Promise.reject(error);
 }
);
//新增響應攔截器
axios.interceptors.response.use(
 response => {
 return response;
 },
 error => {
 return Promise.resolve(error.response);
 }
);
axios.defaults.baseURL = "https://www.xxxx/api";
axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.post["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.timeout = 10000;
function checkStatus(response) {
 return new Promise((resolve, reject) => {
 if (
 response &&
 (response.status === 200 ||
 response.status === 304 ||
 response.status === 400)
 ) {
 resolve(response.data);
 } else {
 reject({
 state: "0",
 message: "網路出現問題"
 });
 }
 });
}
export default {
 post(url, params) {
 return axios({
 method: "post",
 url,
 data: params
 }).then(response => {
 return checkStatus(response);
 });
 },
 get(url, params) {
 params = qs.stringify(params);
 return axios({
 method: "get",
 url,
 params
 }).then(response => {
 return checkStatus(response);
 });
 }
};//如有不懂歡迎加全棧開發交流QQ群:864305860

在vue 專案中,main.js這個檔案

import http from "./utils/http";
Vue.prototype.$http = http;

使用 helloworld.vue

//如有不懂歡迎加全棧開發交流QQ群:864305860
methods: {
 async TestPost() {
 try {
 const res = await this.$http.post("/message/socketid", {
 account: "huangenai"
 });
 console.log(res);
 } catch (error) {
 console.log(error);
 }
 },
 async TestGet() {
 this.$http
 .get("/price")
 .then(res => {
 console.log(res);
 })
 .catch(error => {
 alert(error);
 });
 }
}//如有不懂歡迎加全棧開發交流QQ群:864305860

在main.js中將http.js import 進來 並暴露到全域性使用,在任何vue 頁面中 就不再需要 import http.js了,而直接通過 this. h t t p . p o

s t t h i s . http.post this. http.get 來使用,在checkStatus中統一非同步返回,順便可以處理錯誤的情況。

checkStatus方法 返回了一個 Promise

鏈式結構的話看上面那個get的方法,this.$http.get(…).then(…).catch(…),如果then 裡面又來一個 http請求 會一層包住一層。

function checkStatus(response) {
 return new Promise(resolve => {
 if (
 response &&
 (response.status === 200 ||
 response.status === 304 ||
 response.status === 400)
 ) {
 resolve(response.data);
 } else {
 resolve({
 state: "0",
 message: "網路出現問題"
 });
 }
 });
}