Home  >  Article  >  Web Front-end  >  vue uses axios and encapsulation

vue uses axios and encapsulation

php中世界最好的语言
php中世界最好的语言Original
2018-04-18 14:05:402812browse

This time I will bring you the use of axios and encapsulation in vue. What are the precautions for using axios and encapsulation in vue. The following is a practical case, let's take a look.

First of all, the requirements

1. Need to encapsulate global calls
2. Return a promise object
3. Unify global handling of errors
4. In addition to the login interface token, bring it into the header
5. Automatically save user information to when logging in Inside vuex

First, add the encapsulation code

<strong>/**<br> * User: sheyude<br> * Time: 下午 13:15<br> *<br> */<br>import axios from 'axios';<br>// 导入<a href="http://www.php.cn/code/10545.html" target="_blank">配置文件</a> 配置文件就导入的请求的前缀地址<br>import {defaults} from '@/config/'<br>import storage from './storage'<br>// 这是一个饿了么的弹框<br>import { Message } from 'element-ui';<br>//<a href="http://www.php.cn/code/8586.html" target="_blank">路由</a>配置<br>import router from '@/router'<br>/**<br> * 封装的全局ajax请求<br> */<br>class Axios{<br>  constructor (){<br>    this.init();<br>  };<br>  /**<br>   * 初始化<br>   */<br>  init(){<br>    axios.defaults.baseURL = defaults.baseURL;<br>  };<br>  _setUserInfo(data){<br>    // 把请求的数据存入vuex<br>    store.commit('setUserInfo',data);<br>  /**<br>   * 判断是否是登录<br>   * @param url<br>   * @<a href="http://www.php.cn/wiki/135.html" target="_blank">return</a>s {boolean}<br>   * @private<br>   */<br>  _isLogin(url){<br>    if(url != '/app/login'){<br>      axios.defaults.headers = {'x-token': store.state.user.user.token.token};<br>      return false;<br>    }else{<br>      return true;<br>    }<br>  }<br> <br>  /**<br>   * 判断是否返回数据<br>   * @param data 接收到的数据<br>   * @returns {boolean}<br>   * @private<br>   */<br>  _isStatus(data){<br>    if(data.code == 100){<br>      router.push('/login');<br>      Message.error(data.message || '请重新登录!');<br> <br>      return false<br>    }else{<br>      return true<br>    }<br>  }<br>  /**<br>   * 全局<a href="http://www.php.cn/code/4817.html" target="_blank">错误处理</a><br>   * @param data 传入错误的数据<br>   * @private<br>   */<br>  _error(data){<br>    console.log(data)<br>    Message.error('网络错误!');<br>  }<br> <br>  /**<br>   * GET 请求 {es6解构赋值}<br>   * @param type 包含url信息<br>   * @param data 需要发送的参数<br>   * @returns {Promise}<br>   * @constructor<br>   */<br>  HttpGet({url},data) {<br>    console.log(data)<br>    // 创建一个promise对象<br>    this._isLogin(url)<br>    this.promise = new Promise((resolve, reject)=> {<br>      axios.get(url,{params:data})<br>        .then((data) => {<br>        // console.log(data)<br>          if(this._isStatus(data.data)){<br>            resolve(data.data);<br>          }<br>        })<br>        .catch((data) =>{<br>          this._error(data);<br>        })<br>    })<br>    return this.promise;<br>  };<br>  /**<br>   * POST 请求<br>   * @param type <a href="http://www.php.cn/wiki/60.html" target="_blank">Object</a> 包含url信息<br>   * @param data Object 需要发送的参数<br>   * @param urlData Object 需要拼接到地址栏的参数<br>   * @returns {Promise}<br>   * @constructor<br>   */<br>  HttpPost({url},Data,urlData){<br> <br>    // 判断是否加头部<br>    this._isLogin(url);<br>    // 创建一个promise对象<br>    this.promise = new Promise((resolve, reject)=> {<br>      for(const item in urlData){<br>        url += '/' + urlData[item];<br>      };<br>      axios.post(url,Data)<br>        .then((data) => {<br> <br>          // 是否请求成功<br>          if(this._isStatus(data.data)){<br>            // 是否需要存数据<br>            if(this._isLogin(url)){<br>              this._setUserInfo(data.data)<br>            };<br>            resolve(data.data)<br>          };<br>        })<br>        .catch((data) =>{<br>          this._error(data);<br>        })<br>    })<br>    return this.promise;<br>  };<br>};<br>export default new Axios();</strong>

Calling method

this.$axios.HttpPost(this.audit.auditGet,this.params)
 .then((data) => {
    this.pageData = data.data
 })

Receive 2 parameters

1 url address
2 Parameters that need to be passed

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

How to convert JS types

Delete specified elements from JS array

FileReader in JS implements image upload preview

The above is the detailed content of vue uses axios and encapsulation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn