uni-app的uni.request()請求封裝
阿新 • • 發佈:2021-12-20
第一種:常見的直接發起uni.request()請求
onLoad() {//頁面載入時呼叫 this.getSwipers() }, methods: { //獲取輪播圖資料 getSwipers(){ uni.request({ url:"https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata", method:"GET", success: (res) => { console.log(res) if(res.data.meta.status !== 200){//如果請求失敗,不等於200狀態碼 return uni.showToast({ title:"請求失敗!" }) } //資料請求成功 this.swipers = res.data.message } }) } }
第二種:async修飾函式和await的使用,這個好像是es7的
onLoad() {//頁面載入時呼叫 this.getSwipers() }, methods: { //獲取輪播圖資料 async getSwipers(){ const res = await uni.request({ url:"https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata", method:"GET" //預設是GET,可省 }) console.log(res) } }
第三種:es6非同步promise封裝這種發起請求介面,跟axios封裝差不多
一個專案有N多個介面,但前面的一段url基本是一致不變的(專業點說也就是前面那一段是域名,域名是不變的+後面一段是變化的,是介面地址)。
這時候我們就可以抽離封裝了api了。
api.js//功能:暴露介面 const BASE_URL = 'https://api-hmugo-web.itheima.net' //域名或選取所有介面不變的那一部分 export const myRequest = (options) => { //暴露一個function:myRequest,使用options接收頁面傳過來的引數return new Promise((resolve, reject) => { //非同步封裝介面,使用Promise處理非同步請求 uni.request({ //傳送請求 url: BASE_URL + options.url, //接收請求的API method: options.method || 'GET', //接收請求的方式,如果不傳預設為GET data: options.data || {}, //接收請求的data,不傳預設為空 success: (res) => { //資料獲取成功 if (res.data.meta.status !== 200) { //因為200是返回成功的狀態碼,如果不等於200,則代表獲取失敗, return uni.showToast({ title: "資料獲取失敗!" }) } resolve(res) //成功,將資料返回 }, fail: (err) => { //失敗操作 uni.showToast({ title: "請求介面失敗!" }) reject(err) } }) }) } /*下面程式碼不作用途:僅參照演示,模仿頁面呼叫函式,將實參傳進myRequest,也就是上面myRequest使用(options)接收。 myRequest({ url: '/getInfo', method: 'POST', }) */
在uni-app的main.js中將api.js掛載到全域性,讓所有頁面都能接收
import { myRequest } from './utils/api.js' //掛載到全域性,讓所有頁面都能接收 Vue.prototype.$myRequest = myRequest //掛載到Vue的原型上
頁面呼叫(index.vue想使用):
data() { return { swipers: [] } }, onLoad() { //頁面載入時呼叫 this.getSwipers() }, methods: { //獲取輪播圖資料 async getSwipers() { const res = await this.$myRequest({//呼叫封裝好的API請求函式 url:'/api/public/v1/home/swiperdata',//把介面傳過去 method:'GET', }) console.log(res) this.swipers = res.data.message //儲存值 } }
作者:似朝朝我心
連結:https://www.jianshu.com/p/8276ca362e5c
來源:簡書
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。
uni-app封裝一個request請求 案例二
在上一篇文章裡面,寫到使用uni.request請求的方法
https://www.jianshu.com/p/bc62c9e1beed
getList() { uni.request({ url: "https://unidemo.dcloud.net.cn/api/news", method: 'get', dataType: 'json', success: (res) => { console.log(res.data); this.productList = res.data; }, }); },
但是實際做專案的時候,會發現每個介面都要重複的寫這些,看起來重複又囉嗦,心情就十分的不美麗了。
如果不封裝那麼我們會面臨幾個不方便的地方:
那麼,該怎麼使用uni-app封裝一個request請求?步驟很簡單,且聽我一一道來。
注意:使用的例子,來自於這篇文章的相關的程式碼,修改封裝請求是基於這個文章裡面程式碼。進行相關的修改的。
https://www.jianshu.com/p/bc62c9e1beed
步驟如下:
1、專案下新建common資料夾,再建立request.js檔案
2、開啟request.js檔案,開始寫封裝的程式碼
思路很簡單
定義域名:baseUrl;
定義方法:api;
通過promise非同步請求,最後匯出方法。
request.js參考程式碼如下
const baseUrl = 'https://unidemo.dcloud.net.cn' const request = (url = '', date = {}, type = 'GET', header = { }) => { return new Promise((resolve, reject) => { uni.request({ method: type, url: baseUrl + url, data: date, header: header, dataType: 'json', }).then((response) => { setTimeout(function() { uni.hideLoading(); }, 200); let [error, res] = response; resolve(res.data); }).catch(error => { let [err, res] = error; reject(err) }) }); } export default request
3、在main.js全域性註冊
import request from 'common/request.js' Vue.prototype.$request = request
4、頁面呼叫
this.$request('/api/news', { // 傳參引數名:引數值,如果沒有,就不需要傳 }).then(res => { // 列印呼叫成功回撥 console.log(res) })
頁面呼叫的index.vue
<template> <view> <uni-list v-for="(item,index) in productList" :key="index"> <uni-list-item :title="item.author_name" :note="item.title"></uni-list-item> </uni-list> </view> </template> <script> import uniList from "@/components/uni-list/uni-list.vue" import uniListItem from "@/components/uni-list-item/uni-list-item.vue" export default { components: { uniList, uniListItem }, data() { return { productList: [], }; }, onLoad() { this.getList(); }, methods: { getList() { this.$request('/api/news', { // 傳參引數名:引數值,如果沒有,就不需要傳 // "username": "john", // "key": this.searchValue }).then(res => { // 列印呼叫成功回撥 console.log(res) this.productList = res; }) }, } } </script> <style> </style>