• Welcome to the eight year blog, I'm glad to meet you at the right age!
  • Due to the theme, QQ login partners will display the default avatar in the comments. Please go to the personal center and upload the avatar again.

Vue encapsulates Axios

Code Notes barben 5 months ago (06-05) 332 views 0 comments

And the previous article《 Wechat applet encapsulates request request 》Very similar to the unique for loop writing
The advantage is really clean~

1. Two new interfaces are used to encapsulate and manage new files for Axios

I'm here src/assets/js/api Under the new one index.js and apiList.js


stay index.js To encapsulate Axios:

 Import Axios from 'Axios'; 
 import {message} from' element UI '; 
 import apilist from'. / apilist '; 
 import store from' @ / store '; 



axios. Defaults. Timeout = 5000; / / timeout termination request 
 Axios. Defaults. Baseurl ='http: / / 192.168.0.88:8080 /'; /// / set a request interceptor (axios.interceptors.request.use (
 config = > {
 / / const token = getcookie ('name '); / / note that you need to introduce cookie methods when using them, and recommend that js-cookie.config.data = json.stringify (config.data); 
, config.headers = {content-type':'application///content-type ':'application///application///content-type':'application / application / content-type ':'application / application / content-type':'application / application / content-type ':'application / application / content-type':'application / application / content-type ':'application / content-type':'application / application / application / content-type '':'application / application / type ''content-type''content-type JSON; charset = UTF-8 ', 
        // 'Content-Type':'application/x-www-form-urlencoded'
    }
    if(store.state.token) {
      config.headers['Authorization'] = store.state.token;
    }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
); / / set a response interceptor (axios.interceptors.response.use (
response = > {
 / / if (response.data.errcode = = 2) {use / / / / route.push ({path: "/ login", 
 / / query: {redirect: router.currentroute.fullpath.fullpath} / / / / jump from which page to jump from 
 / / / jump from which page 
 / / / jump from which page 
 / / / / jump from which page 
 / / / jump from which page 
 / / / jump from which page 
 / / / jump from which page 
 / / / jump from which page 
 / / / / jump from which page 
 / / / jump from which page 
 / / / / / / / / / / / /}) 
 / / return response; 
 / / let res = response. Data; //Get the data returned by the response 
 if (res.code = = 200) {return res.data; 
} else {
 / / if the status code is not 200, an error will be reported. An error message will pop up, and no data will be returned 
} error (res.msg); 
}, 
 
 error = > {message. Error (error. Message); Return promise. Reject (error) 
} 
) 
 / / the following is the encapsulation method: 
 / / in the get delete request mode, the first parameter is the URL address of the request, and the second parameter is some configuration items of the request. The parameters to be passed to the back end are included in the data or params properties of the configuration item, 
 / / Post put In the patch request, the first parameter is the URL address, the second parameter is the JSON data to be input, and the third parameter is other configuration items other than the input parameter. 

var list = {};

for(let item in apiList) {
  list[item] = function(params) {
    let [method, url] = apiList[item];
    let data = (method == 'get' || method == "delete") ? {params} : (method == 'post' || method == "put" || method == "patch") ? params : {}
    return new Promise((resolve, reject) => {
      axios[method](url, data)
    . then (RES = > {if (RES) {
 / / in the response interceptor, if the code is not 200, no data is returned, and res may be undefined. Therefore, if res has data, it can be sent out with resolve. 
          resolve(res);
        }
      })
      .catch(err => {
        reject(err);
      })
    })
  }
}

export default list;

stay apiList.js All interfaces are managed in a unified way

 Let apilist = {
login: ["post", "/ user / login"], / / the user logs in 
, getcaptcha: ["get", "/ user / captcha"], / / get the login image verification code 
 
 logout: ["get", "/ user / logout"], / / user logs out 
} export default apilist;

2. Introduce in main.js

 Import HTTP from '@ / assets / JS / API'; / / import the interface list 
 Vue. Prototype. $HTTP = http; / / mount the interface list to the global

3. Use encapsulated methods in pages

 let params = {
  username: "barben",
  password: "12345678"
}

this.$http.login(params)
.then(res => {
  console.log(res);
})
.catch(err => {
  console.log(err);
})

 


Eight blogs that year, we've been there all the time
If the author does not indicate the original article, please indicate the link and source of this article
Vue encapsulates Axios - https://www.barben.cn/code/845.html
Like it( two )
Post my comments
Cancel comment
expression Mapping Bold Strikethrough Center Italics

You need to bring your nickname and email with you in the year of eight!

  • Nickname (required)
  • Email address (required)
  • website