国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

vue項目中axios請求網絡接口封裝的示例代碼

2019-11-19 12:20:13
字體:
來源:轉載
供稿:網友

每個項目網絡請求接口封裝都是很重要的一塊,第一次做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//請求返回數據  })

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 盐山县| 桦南县| 富宁县| 富源县| 白沙| 同江市| 广饶县| 驻马店市| 会同县| 和平县| 合水县| 章丘市| 兴山县| 黔南| 棋牌| 北川| 涟源市| 顺昌县| 文水县| 珲春市| 应用必备| 罗山县| 宁蒗| 富宁县| 漾濞| 同江市| 娱乐| 临颍县| 教育| 读书| 龙泉市| 蒲江县| 嘉鱼县| 越西县| 河北省| 山东省| 阳春市| 遵义县| 鞍山市| 固原市| 沾化县|