每個項目網絡請求接口封裝都是很重要的一塊,第一次做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 = {}) { // 創建動畫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 = getHttpVue.prototype.$postHttp = postHttp//get網絡請求 this.$getHttp(this.$shopUrl + 'api/product/list',) .then((response) => { response.result//請求返回數據 }) // post網絡請求 this.$postHttp(this.$shopUrl + 'api/product/list',) .then((response) => { response.result//請求返回數據 })以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答