前端uniapp封裝網(wǎng)絡(luò)請(qǐng)求以及實(shí)際應(yīng)用教程
1、common文件夾下http.api.js,定義接口
const install = (Vue, vm) => {
//驗(yàn)證碼登陸
let mobilelogin = (params = {}) => vm.$u.http.post('api/user/mobilelogin', params);
// 將各個(gè)定義的接口名稱(chēng),統(tǒng)一放進(jìn)對(duì)象掛載到vm.$u.http.api(因?yàn)関m就是this,也即this.$u.http.api)下
vm.$u.api = {
mobilelogin,
};
}
export default {
install
}2、common文件夾下http.interceptor.js,請(qǐng)求封裝
// 此vm參數(shù)為頁(yè)面的實(shí)例,可以通過(guò)它引用vuex中的變量
import Vue from 'vue'
module.exports = (vm) => {
// 初始化請(qǐng)求配置
uni.$u.http.setConfig((config) => {
/* config 為默認(rèn)全局配置*/
config.baseURL = 'xxxxxxx'; /* 根域名 */
config.header = {
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
}
return config
})
// 請(qǐng)求攔截
uni.$u.http.interceptors.request.use((config) => {
config.header.token = Vue.prototype.$store.state.member.token
config.header.lang = Vue.prototype.$store.state.lang;
console.log(config, 'config');
return config
})
// 響應(yīng)攔截
uni.$u.http.interceptors.response.use((res) => {
console.log(res, '成功')
if (res.statusCode == 200) {
// res為服務(wù)端返回值,可能有code,result等字段
// 這里對(duì)res.result進(jìn)行返回,將會(huì)在this.$u.post(url).then(res => {})的then回調(diào)中的res的到
// 如果配置了originalData為true,請(qǐng)留意這里的返回值
console.log(res.hasOwnProperty('data'));
if (res.hasOwnProperty('data')) {
if (res.data.hasOwnProperty('code') && res.data.code == 1) {
if (res.data.msg != "" && res.data.msg != "success" && res.data.msg != 'ok') {
uni.$u.toast(res.data.msg)
// return res.data.data;
}
return res.data.data;
} else {
uni.$u.toast(res);
if (res.data.hasOwnProperty('msg')) {
uni.$u.toast(res.data.msg);
} else {
console.log(res);
uni.$u.toast('返回參數(shù)錯(cuò)誤', res);
}
return false;
}
} else {
uni.$u.toast('不能識(shí)別數(shù)據(jù)1')
return false;
}
}
return res
}, (res1) => {
/* 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么 (statusCode !== 200)*/
console.log(res1, '失敗')
if (res1.statusCode == 401) {
// 假設(shè)401為token失效,這里跳轉(zhuǎn)登錄
uni.$u.toast('請(qǐng)登錄后操作');
console.log(Vue.prototype.$store, 'Vue.prototype.$store');
Vue.prototype.$store.commit('SET_MEMBER', {})
setTimeout(() => {
// 此為uView的方法,詳見(jiàn)路由相關(guān)文檔
uni.$u.route({
url: '/pages/login/login',
})
}, 1500)
return res1.data;
} else {
uni.$u.toast('不能識(shí)別數(shù)據(jù)2');
// 如果返回false,則會(huì)調(diào)用Promise的reject回調(diào),
// 并將進(jìn)入this.$u.post(url).then().catch(res=>{})的catch回調(diào)中,res為服務(wù)端的返回值
return false;
}
return Promise.reject(res)
})
}3、全局?jǐn)?shù)據(jù)定義 store文件夾下index.js
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)
const store = new Vuex.Store({
plugins: [
// 可以有多個(gè)持久化實(shí)例
createPersistedState({
key: 'app_config_data', // 狀態(tài)保存到本地的 key
paths: ['member', 'cookieKey'], // 要持久化的狀態(tài),在state里面取,如果有嵌套,可以 a.b.c
storage: { // 存儲(chǔ)方式定義
getItem: (key) => uni.getStorageSync(key), // 獲取
setItem: (key, value) => uni.setStorageSync(key, value), // 存儲(chǔ)
removeItem: (key) => uni.removeStorageSync(key) // 刪除
}
})
],
state: {
store: {},
cart: [],
orderType: 'takein',
address: {},
addresses: [],
member: {
// avatar: "http://cdn.shop.weivee.com/shop/20200408/6162b21922f336ae9b320bc06582ab7f.png",
// birthday: null,
// couponNum: 0,
// currentValue: "1.00",
// gender: 0,
// id: 2,
// level: 1,
// mobile: "15975073045",
// money: "4789.20",
// openid: "oEY7Y5XYukLQySoKA7sPGWSDtktA",
// score: 0,
// token: "cb3136ea-97d3-42d3-a676-15ed170fa725",
// token: "",
// username: "游客"
},
openid:"",
lang: 'zh-cn',
cookieKey:'PHPSESSID=e4dk4o2utr3c0n95tp42p745ai',
// 默認(rèn)地為你為北京地址
location: {},
tableNumber:''
},
getters: {
isLogin: state => Object.keys(state.member).length > 0 //是否登錄
},
mutations: {
SET_ORDER_TYPE(state, type) {
state.orderType = type
},
SET_MEMBER(state, member) {
state.member = member
},
SET_ADDRESS(state, address) {
state.address = address
},
SET_ADDRESSES(state, addresses) {
state.addresses = addresses
},
SET_STORE(state, store) {
state.store = store
},
SET_CART(state, cart) {
state.cart = cart
},
REMOVE_CART(state) {
state.cart = []
},
setCookie(state, provider) {
state.cookie = provider;
uni.setStorage({
key: 'cookieKey',
data: provider
});
},
SET_LOCATION(state, location) {
state.location = location;
},
SET_OPENID(state, openid) {
state.openid = openid;
},
SET_TABLE_NUMBER(state, tableNumber) {
state.tableNumber = tableNumber
},
},
actions: {
}
})
export default store注意:vuex的使用前要先導(dǎo)入vuex(npm i vuex),在該方法中還需導(dǎo)入vuex-persistedstate(npm i vuex-persistedstate)

4、main.js中聲明(例子中用的比較雜,挑有用的使用)
import App from './App'
import store from './store'
// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
// console.log(Vue.prototype.$store);
Vue.prototype.$store = store
console.log(Vue.prototype.$store);
App.mpType = 'app'
// main.js
import uView from "uview-ui";
Vue.use(uView);
const app = new Vue({
store,
...App
})
// http攔截器,將此部分放在new Vue()和app.$mount()之間,才能App.vue中正常使用
import httpInterceptor from '@/common/http.interceptor.js'
Vue.use(httpInterceptor, app)
// http接口API集中管理引入部分
import httpApi from '@/common/http.api.js'
Vue.use(httpApi, app)
Vue.prototype.$store = store
console.log(Vue.prototype.$store);
Vue.prototype.$util = util
Vue.prototype.$baseUrl = 'xxxx'//根域名
app.$mount()
// #endif
// #ifdef VUE3
import {
createSSRApp
} from 'vue'
export function createApp() {
const app = createSSRApp(App)
return {
app
}
}
// #endif5、接下來(lái)就是在頁(yè)面中發(fā)實(shí)際應(yīng)用了
let data = await this.$u.api.mobilelogin({
//所傳參數(shù)
mobile: _this.tel,
captcha: _this.code,
type: 1
});
console.log(data, 'data');這里輸出的data 與common文件夾下http.interceptor.js的配置有關(guān),我這里直接獲取的是網(wǎng)絡(luò)請(qǐng)求中data.data的數(shù)據(jù)

以上是網(wǎng)絡(luò)請(qǐng)求的邏輯說(shuō)明以及部分代碼,關(guān)于vuex的詳細(xì)使用可以點(diǎn)擊這里:m.fzitv.net/article/254722.htm
總結(jié)
到此這篇關(guān)于前端uniapp封裝網(wǎng)絡(luò)請(qǐng)求以及實(shí)際應(yīng)用的文章就介紹到這了,更多相關(guān)前端uniapp封裝網(wǎng)絡(luò)請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
bootstrap-paginator服務(wù)器端分頁(yè)使用方法詳解
這篇文章主要為大家詳細(xì)介紹了bootstrap-paginator服務(wù)器端分頁(yè)的使用方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-02-02
再談javascript圖片預(yù)加載技術(shù)(詳細(xì)演示)
由于javascript無(wú)法獲取img文件頭數(shù)據(jù),必須等待其加載完畢后才能獲取真實(shí)的大小,所以lightbox類(lèi)效果為了讓圖片居中顯示,導(dǎo)致其速度體驗(yàn)要比直接輸出的差很多。2011-03-03
JS動(dòng)態(tài)高度虛擬列表實(shí)現(xiàn)原理解析
這篇文章將和大家一起探討一下動(dòng)態(tài)高度虛擬列表原理并指出常見(jiàn)虛擬列表采用累計(jì)高度方式存在缺點(diǎn),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11
textContent在Firefox下與innerText等效的屬性
textContent在Firefox下與innerText等效的屬性...2007-05-05
Tesseract.js使用純js實(shí)現(xiàn)的OCR文字識(shí)別
Tesseract.js是流行的Tesseract OCR引擎的純Javascript端口,這個(gè)庫(kù)支持100多種語(yǔ)言,自動(dòng)文本定位和腳本檢測(cè),一個(gè)簡(jiǎn)單的界面,用于閱讀段落、單詞和字符邊界框,Tesseract.js既可以在瀏覽器中運(yùn)行,也可以在帶有NodeJS的服務(wù)器上運(yùn)行2023-10-10
javascript實(shí)現(xiàn)智能手環(huán)時(shí)間顯示
這篇文章主要為大家詳細(xì)介紹了javascript實(shí)現(xiàn)智能手環(huán)時(shí)間顯示,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-09-09
離開(kāi)當(dāng)前頁(yè)面前使用js判斷條件提示是否要離開(kāi)頁(yè)面
這篇文章主要介紹了離開(kāi)當(dāng)前頁(yè)面前如何使用js判斷條件提示是否要離開(kāi)頁(yè)面,需要的朋友可以參考下2014-05-05
小程序?qū)崿F(xiàn)分頁(yè)查詢(xún)列表的模板
這篇文章主要為大家詳細(xì)介紹了小程序?qū)崿F(xiàn)分頁(yè)查詢(xún)列表的模板,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08

