封裝:
// 新建目錄util 目錄下api.js const BASE_URL = 'http://localhost:8080'; export const myRequest = (options) => { return new Promise((resolve,reject)=>{ uni.request({ url:BASE_URL+options.url, method:options.method || "GET", data:options.data || {}, success:(res)=>{ if(res.data.status !== 0){ return uni.showToast({ title:"獲取數據失敗" }) } resove(res) }, fail:(err)=>{ return uni.showToast({ title:"請求接口失敗" }) reject(err) } }) }) } // myRequest({ // url:'/api/getlunbo', // method:"POST", // data:{ // }, // })
幾乎每個頁面都會使用,則通過入口文件main.js引入
// main.js
import Vue from 'vue' import App from './App' import {myRequest} from './util/api.js' //引入 Vue.prototype.$myRequest = myRequest //通過Vue.prototype掛載至全局 Vue.config.productionTip = false App.mpType = 'app' const app = new Vue({ ...App }) app.$mount()
使用:
methods: { //獲取輪播圖數據 (1)// getSwipers(){ // uni.request({ // url:'../../common/util.json', // success:res=>{// this.swiper= res.data.message // } // }) // },
(3)
async getSwipers (){ const res = await this.$myRequest({ url:'/api/getlunbo' }) this.swiper = res.data.message }, (2)// getSwipers (){ // this.$myRequest({ // url:"/api/getlunbo" // }) //返回promise函數,可改為以上方法 通過await async進行修飾 // } }
