vue中axios使用封装

时间:2019-12-12
本文章向大家介绍vue中axios使用封装,主要包括vue中axios使用封装使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、在main.js导入

// 引入axios,并加到原型链中
import axios from 'axios';
Vue.prototype.$axios = axios;
import QS from 'qs'
Vue.prototype.qs = QS;

二、创建http.js文件(与main.js一级)

import axios from 'axios';
import qs
from 'qs';//转换请求参数格式,需要时使用 axios.defaults.baseURL = process.env.BASE_API; axios.defaults.timeout = 5000; // 添加请求拦截器 axios.interceptors.request.use(function (config) { // 在发送请求之前做些什么,例如加入token //config.headers.Authorization = '123'; return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器 axios.interceptors.response.use(function (response) { // 在接收响应做些什么,例如跳转到登录页 return response; }, function (error) { // 对响应错误做点什么 return Promise.reject(error); }); //返回一个Promise(发送post请求) export function fetchPost(url,params){ return new Promise((resolve, reject) => {//ES6构造函数 -- 待学习 axios.post(url, params) .then(response => { resolve(response); }, err => { reject(err); }) .catch((error) => { reject(error) }); }); } //返回一个Promise(发送get请求) export function fetchGet(url, param) { return new Promise((resolve, reject) => { axios.get(url, {params: param}) .then(response => { resolve(response) }, err => { reject(err) }) .catch((error) => { reject(error) }) }) } export default { fetchGet, fetchPost }

三、在要使用的vue模块导入并使用

import https from '../https.js'   // 注意用自己的路径

// 请求后台数据==================
            loginPost: function () {
                let params ={'username': 'admin', 'password': 'admin123', 'rememberMe': 'true','isMobile':'1'}
                https.fetchPost('/login',params ).then((data) => {
                    this.base.token = data.data.token    
                    // console.log("this.base.tokenthis.base.token",this.base.token)
                    this.indexPost2(this.rres)
                }).catch(err=>{
                        console.log(err)
                    }
                )
            },
            indexPost2:function (date) {
                var this_ = this
                this_.check = false
                var jobj ={data:{'menuDate': date,'token':this.base.token}}
                let string  = JSON.stringify(jobj)
                let params = {dailyInfo:string}
                https.fetchPost('/meals/mobile/getDailyMenuByDate', params)
                .then((data) => {
                    this_.base.indexData = data
                    this_.check = true
                    // console.log('thenthenthenthen',data)
                })
                .catch((err)=>{
                    console.log(err)

                })
            },
            // ================================================
        },

原文地址:https://www.cnblogs.com/1156063074hp/p/12030288.html