vue项目中axios的接口请求封装

315 阅读2分钟

安装axios:npm install axios src下新建common文件夹 ###1.common下创建serviceUrl.js文件 用来判断当前的环境

let host = ''

if (process.env.NODE_ENV === 'development') {
   // 开发环境
   host = 'http://lvcai.xj128.com'
} else if (process.env.NODE_ENV === 'production') {
   // 生产环境
   host = 'http://lvcai.xj128.com'
}
export default host

###2.common下创建common.js文件 用来封装公共的函数

//导入main.js这里需要用到路由
import _this from '../main'

// 设置localStorage
function setStorage (name, content) {
    if (!name) return
    if (typeof content !== 'string') {
        content = JSON.stringify(content)
    }
    window.localStorage.setItem(name, content)
}

// 获取localStorage
function getStorage (name) {
    if (!name) return
    return window.localStorage.getItem(name)
}

// 删除localStorage
function removeStorage (name) {
    if (!name) return
    window.localStorage.removeItem(name)
}

// 把obj对象里的值覆盖到newobj里面
function deepCopy (newobj, obj) {
    if (typeof obj !== 'object') {
        return obj
    }
    for (let attr in obj) {
        let a = {}
        if (newobj[attr]) {
            a = newobj[attr]
        }
        newobj[attr] = deepCopy(a, obj[attr])
    }
    return newobj
}

// 跳转到登陆页面
function jumpToLogin () {
    _this.$router.push({
        path: '/login',
        query: {
            redirect: _this.$route.fullPath
        }
    })
}

// 当出错的时候,显示错误信息,并且跳转
function errorToBack (msg = '出错了,请重试', time = 1500) {
    _this.$dialog.toast({
        mes: msg,
        timeout: time
    })
}
// 操作成功后,的提示信息
function successToShow (msg = '保存成功', callback = function () {}) {
    wx.showToast({
      title: msg,
      icon: 'success',
      duration: 2000,
    });
    setTimeout(function () {
      callback();
    }, 1500)
}

// 时间戳转时间格式
function timeToDate (date) {
    let dateTime = new Date(date * 1000) // 如果date为13位不需要乘1000
    let Y = dateTime.getFullYear() + '-'
    let M = (dateTime.getMonth() + 1 < 10 ? '0' + (dateTime.getMonth() + 1) : dateTime.getMonth() + 1) + '-'
    let D = (dateTime.getDate() < 10 ? '0' + (dateTime.getDate()) : dateTime.getDate()) + ' '
    let h = (dateTime.getHours() < 10 ? '0' + dateTime.getHours() : dateTime.getHours()) + ':'
    let m = (dateTime.getMinutes() < 10 ? '0' + dateTime.getMinutes() : dateTime.getMinutes()) + ':'
    let s = (dateTime.getSeconds() < 10 ? '0' + dateTime.getSeconds() : dateTime.getSeconds())
    return Y + M + D + h + m + s
}

// 货币格式化
function formatMoney (number, places, symbol, thousand, decimal) {
    number = number || 0
    places = !isNaN(places = Math.abs(places)) ? places : 2
    symbol = symbol !== undefined ? symbol : '¥'
    thousand = thousand || ','
    decimal = decimal || '.'
    let negative = number < 0 ? '-' : ''
    let i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + ''
    let j = (i.length) > 3 ? i.length % 3 : 0
    return symbol + negative + (j ? i.substr(0, j) + thousand : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : '')
}

//节流函数,防止多次点击调用接口
function throttle (fn, context, delay) {
    clearTimeout(fn.timeoutId)
    fn.timeoutId = setTimeout(function () {
        fn.call(context)
    }, delay)
}


export default {
    setStorage: setStorage,
    getStorage: getStorage,
    removeStorage: removeStorage,
    deepCopy: deepCopy,
    jumpToLogin: jumpToLogin,
    timeToDate: timeToDate,
    formatMoney: formatMoney,
    errorToBack: errorToBack,
    successToShow: successToShow,
    throttle: throttle
}

###3.common下创建api.js文件 封装所有的网络请求接口

import axios from 'axios'
//网络请求的序列化
import qs from 'qs'
import _this from '../main'
import common from './common'
import host from './serviceUrl'

// 需要登陆的,都写到这里,否则就是不需要登陆的接口
let methodToken = [
    'user.info',
    'user.editinfo'
]

// 接口token验证
const post = (method, data, callback) => {
    // 如果是需要登陆的,增加token
    if (methodToken.indexOf(method) >= 0) {
        let userToken = common.getStorage('user_token')
        if (!userToken) {
            common.jumpToLogin()
            return false
        } else {
            data.token = userToken
        }
    }
    data.method = method
    sendPost(apiUrl, qs.stringify(data), {}, callback)
}

// axios 发送请求统一处理
const sendPost = (url, data, callback) => {
    _this.$dialog.loading.open('加载中');
    axios.post(url, data, config).then(response => {
        _this.$dialog.loading.close()
        if (!response.data.status) {
            // 输出错误显示
            common.errorToBack(response.data.msg)
            if (response.data.data === 14007 || response.data.data === 14006) {
                // 用户未登录或者token过期 清空本地user_token
                common.removeStorage('user_token')
                // 跳转至登录
                common.jumpToLogin()
            }
        }
        callback(response.data)
    }).catch(err => {
        if (err && err.response) {
            switch (err.response.status) {
                case 400:
                    err.message = '请求参数错误'
                    break
                case 401:
                    err.message = '未授权,请登录'
                    break
                case 403:
                    err.message = '跨域拒绝访问'
                    break
                case 404:
                    err.message = `请求地址出错: ${err.response.config.url}`
                    break
                case 408:
                    err.message = '请求超时'
                    break
                case 500:
                    err.message = '服务器内部错误'
                    break
                case 501:
                    err.message = '服务未实现'
                    break
                case 502:
                    err.message = '网关错误'
                    break
                case 503:
                    err.message = '服务不可用'
                    break
                case 504:
                    err.message = '网关超时'
                    break
                case 505:
                    err.message = 'HTTP版本不受支持'
                    break
                default:
                    break
            }
            _this.$dialog.loading.close()
            common.errorToBack(err.message)
        }
    })
}


// 获取店铺配置
export const shopConfig = () => axios.get(host + '/api/common/jshopconf').then(response => response.data)

// 用户注册
export const reg = (data, callback) => post('user.reg', data, callback)

// 用户登录
export const login = (data, callback) => post('user.login', data, callback)

###4.main.js文件中导入

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import * as Api from './common/api'

Vue.prototype.$api = Api
Vue.config.productionTip = false

new Vue({
 router,
 store,
 render: h => h(App)
}).$mount('#app')