uniapp封装request 的学习指南
前言
只要是前端,不管什么框架和语言,都避免不了和服务端请求数据,以下是uniapp提供的APIuni.request
uni.request({ url: 'https://www.example.com/request', data: { text: 'uni.request' }, header: { 'custom-header': 'hello' }, success: (res) => { console.log(res.data); this.text = 'request success'; } });
|
为了提高开发效率,封装可以使开发过程更加的酣畅淋漓。
实现
一般选择在外面的根目录下,创建utils
文件夹,utils
文件夹下创建http.js
和request.js
utils/http.js
utils/request.js
request.js
封装request请求的文件
import config from "@/config"; import storage from "./storage";
export default { console(options){ if(config.debug){ } }, domain(){ return config.uni_app_web_api_url.replace("api",""); }, send(options={}){ uni.showLoading({ title: '加载中' }); options.url = config.uni_app_web_api_url + '' + options.url; options.method = options.method || "GET"; let users = storage.getJson("users"); if(users != null){ options.header = { "Auth-Token" : users.token }; } this.console(options); return new Promise((resolve, reject) =>{ uni.request(options).then(data=>{ var [error, res] = data; if(error != null){ reject(error); }else{ if(res.data.status == '-1001'){ uni.hideLoading(); uni.navigateTo({ url: '/pages/Login/login/login' }); }else{ resolve(res.data); } } }); }); }, get(url="",data={}){ return this.send({ url: url, data: data }); }, post(url="",data={}){ return this.send({ url: url, data: data, method: "POST" }); } };
|
- 平时用的多的主要还是
get
和post
,因此就封装了两个,如果还有更多的,可以把里面的内容单独提取出来,然后再定义put
、delete
等方法
http.js
封装的api
接口
import request from './request'
export function getBannerList(params) { return new Promise((resolve, reject)=>{ request.get("/banner/getList", params).then((result)=>{ resolve(result) }).catch(err=>{ reject(err) }); }); }
export function addBanner(params) { return new Promise((resolve, reject) => { request.post("/banner/add", params).then((result)=>{ resolve(result); }).catch((error)=>{ reject(error); }); }); }
export function httpGet(url, params) { return new Promise((resolve, reject)=>{ request.get(url, params).then((result)=>{ resolve(result) }).catch(err=>{ reject(err) }); }); }
export function httpPost(url, params) { return new Promise((resolve, reject)=>{ request.post(url, params).then((result)=>{ resolve(result) }).catch(err=>{ reject(err) }); }); }
|
实际使用
在页面使用
<template> <view class="page"> </view> </template>
<script> export default { data() { return { bannerList: [], }; }, onLoad() { this.loadData(); }, methods: { loadData() { this.$http .getBannerList() .then((res) => { if (res.code == 1) { res.banner.forEach((val) => { val = this.$config.uni_app_web_url + val; });
this.bannerList = res.data; } else { uni.showToast({ title: "网络错误,请重试~", icon: "none", duration: 2000, }); } }) .catch((error) => { console.log(error); });
}, }, }; </script>
<style scoped lang="scss"> </style>
|
- 以下还有几个配置文件,磨刀不误砍柴工,都可以放在
utils
目录下
配置文件
config.js
此文件放在根目录,和main.js
同级即可
export default { web_name: "网站名称", uni_app_web_url: "http://baidu.com/", uni_app_web_api_url: "http://baidu.com/api", debug: true }
|
storage.js
缓存封装,一些需要用的数据,可以放进去,类似token,语言,主题之类的。
export default { set(name,value){ uni.setStorageSync(name,value); }, setJson(name,value){ uni.setStorageSync(name,JSON.stringify(value)); }, get(name){ return uni.getStorageSync(name); }, getJson(name){ const content = uni.getStorageSync(name); if(!content){ return null; } return JSON.parse(content); }, remove(name){ uni.removeStorageSync(name); }, clear(){ uni.clearStorageSync(); } };
|
main.js
这是根目录下的main.js
import Vue from 'vue'; import App from './App';
import * as http from './utils/http' import * as utils from './utils/utils' import * as common from './utils/common' import store from './store' import storage from 'utils/storage' import config from '@/config'
Vue.prototype.$store = store Vue.prototype.$storage = storage Vue.prototype.$http = http Vue.prototype.$utils = utils Vue.prototype.$common = common Vue.prototype.$config = config
App.mpType = 'app' const app = new Vue({ ...App }) app.$mount()
|
扩展
utils.js
很多可以公共使用的方法,为你准备好了
export function msg(content,time=3000){ uni.showToast({ icon:'none', title: content, duration: time }); }
export function showLoading(content="加载数据中...",mask=true){ uni.showLoading({ title: content, mask: mask }); }
export function hideLoading(timer=0){ if(timer > 0){ var t = setTimeout(function () { uni.hideLoading(); clearTimeout(t); }, timer); }else{ uni.hideLoading(); } }
export function in_array(search,array){ let flag = false; for(let i in array){ if(array[i]==search){ flag = true; break; } }
return flag; }
export function isDataType(data,type){ return Object.prototype.toString.call(data) === '[object '+type+']'; }
export function ltrim(str,char){ let pos = str.indexOf(char); let sonstr = str.substr(pos+1); return sonstr; }
export function rtrim(str,char){ let pos = str.lastIndexOf(char); let sonstr = str.substr(0,pos); return sonstr; }
export function navigateTo(url,params){ uni.navigateTo({ url: parseUrl(url,params) }) }
export function redirectTo(url,params){ uni.redirectTo({ url: parseUrl(url,params) }); }
export function reLaunch(url,params){ uni.reLaunch({ url: parseUrl(url,params) }); }
export function switchTab(url,params){ uni.switchTab({ url: parseUrl(url,params) }); }
export function navigateBack(delta){ uni.navigateBack({ delta: delta }); }
export function preloadPage(url, params){ uni.preloadPage({ url: parseUrl(url,params) }); }
export function prePage(){ let pages = getCurrentPages(); let prePage = pages[pages.length - 2]; return prePage; return prePage.$vm; }
export function rpx2px(num){ return uni.upx2px(num); }
export function px2rpx(num){ return num/(uni.upx2px(num)/num); }
export function getSystemInfo(){ const info = uni.getSystemInfoSync(); return { w: info.windowWidth, h: info.windowHeight }; }
function parseUrl(url,params){ let arr = []; let string = ''; for(let i in params){ arr.push(i + "=" + params[i]); } string = "/pages/" + url; if(arr.length > 0){ string += "?" + arr.join("&"); } return string; }
|
使用
this.$utils.msg("消息提示") this.$utils.navigateTo("login")
|
store/index.js
根目录下创建store
,里面的index.js
,这里参考vuex
import Vue from 'vue' import Vuex from 'vuex' import storage from '../common/storage'
Vue.use(Vuex);
const store = new Vuex.Store({ state: { users: storage.getJson("users") }, getters: { getCart: state => { let users = storage.getJson("users"); if(users == null){ return 0; }
return users.shop_count; } }, mutations: { UPDATEUSERS(state, data){ state.users = data; storage.setJson("users",data); }, DELETEUSERS(state,name){ state.users = null; storage.remove(name); }, UPDATECART(state, data){ state.users.shop_count = data; let users = storage.getJson("users"); users.shop_count = data; storage.setJson("users",users); } }, actions: { getCart(context){ }, usersStatus(context){ return new Promise(function (resolve, reject) { if(storage.getJson("users") == null){ reject(); }else{ resolve(); } }); } } })
export default store
|
这是比较全面的文件,大家可以根据自己的情况来引入文件,如果只是单单的接口请求,那就上面的几个文件,扩展文件不用即可。