每個(gè)項(xiàng)目網(wǎng)絡(luò)請(qǐng)求接口封裝都是很重要的一塊,第一次做Vue項(xiàng)目,我們的封裝方法如下:
(1).新建一個(gè)js文件,取名api.js
(2).引入 axios ,mint-UI ,如下圖:
import axios from 'axios' import {MessageBox, Toast} from 'mint-ui' axios.defaults.timeout = 50000//默認(rèn)請(qǐng)求超時(shí)時(shí)間 axios.defaults.headers = '請(qǐng)求頭'
(2).封裝get方法
export function getHttp (url, params = {}) { // 創(chuàng)建動(dòng)畫(huà)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() // // 關(guān)閉動(dòng)畫(huà) }) .catch(err => { reject(err) Indicator.close() // // 關(guān)閉動(dòng)畫(huà) 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() // // 關(guān)閉動(dòng)畫(huà) }, (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)絡(luò)請(qǐng)求 this.$getHttp(this.$shopUrl + 'api/product/list',) .then((response) => { response.result//請(qǐng)求返回?cái)?shù)據(jù) }) // post網(wǎng)絡(luò)請(qǐng)求 this.$postHttp(this.$shopUrl + 'api/product/list',) .then((response) => { response.result//請(qǐng)求返回?cái)?shù)據(jù) })
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com