vue項目中axios請求網(wǎng)絡接口封裝的示例代碼
更新時間:2018年12月18日 08:23:42 作者:honey緣木魚
這篇文章主要介紹了vue項目中axios請求網(wǎng)絡接口封裝的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
每個項目網(wǎng)絡請求接口封裝都是很重要的一塊,第一次做Vue項目,我們的封裝方法如下:
(1).新建一個js文件,取名api.js
(2).引入 axios ,mint-UI ,如下圖:
import axios from 'axios' import {MessageBox, Toast} from 'mint-ui' axios.defaults.timeout = 50000//默認請求超時時間 axios.defaults.headers = '請求頭'
(2).封裝get方法
export function getHttp (url, params = {}) { // 創(chuàng)建動畫mint-ui Indicator.open({ text: '加載中...', spinnerType: 'fading-circle' }) return new Promise((resolve, reject) => { axios.get(url, { params: params }) .then(response => { resolve(response.data) Indicator.close() // // 關閉動畫 }) .catch(err => { reject(err) Indicator.close() // // 關閉動畫 MessageBox.alert('message', err) }) }) }
(4).封裝post方法
export function postHttp (url, data = {}) { Indicator.open({ text: '加載中...', spinnerType: 'fading-circle' }) return new Promise((resolve, reject) => { axios.post(url, data) .then(response => { if (response.data.status == 1) { resolve(response.data) } else { Toast(response.data.msg) } Indicator.close() // // 關閉動畫 }, (err) => { reject(err) Indicator.close() }) }) }
(5).封裝后方法的使用
在main.js中引入全局變量
import {getHttp, postHttp} from './config/api' Vue.prototype.$getHttp = getHttp Vue.prototype.$postHttp = postHttp //get網(wǎng)絡請求 this.$getHttp(this.$shopUrl + 'api/product/list',) .then((response) => { response.result//請求返回數(shù)據(jù) }) // post網(wǎng)絡請求 this.$postHttp(this.$shopUrl + 'api/product/list',) .then((response) => { response.result//請求返回數(shù)據(jù) })
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue+Element-ui的el-table的多級內(nèi)容渲染問題
這篇文章主要介紹了vue+Element-ui的el-table的多級內(nèi)容渲染問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10vuejs+element-ui+laravel5.4上傳文件的示例代碼
本篇文章主要介紹了vuejs+element-ui+laravel5.4上傳文件的示例代碼,具有一定的參考價值,有興趣的可以了解一下2017-08-08在vue react中如何使用Web Components組件
這篇文章主要介紹了在vue react中如何使用Web Components組件問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05