前端uniapp封裝網(wǎng)絡(luò)請求以及實際應(yīng)用教程
1、common文件夾下http.api.js,定義接口
const install = (Vue, vm) => {
//驗證碼登陸
let mobilelogin = (params = {}) => vm.$u.http.post('api/user/mobilelogin', params);
// 將各個定義的接口名稱,統(tǒng)一放進(jìn)對象掛載到vm.$u.http.api(因為vm就是this,也即this.$u.http.api)下
vm.$u.api = {
mobilelogin,
};
}
export default {
install
}2、common文件夾下http.interceptor.js,請求封裝
// 此vm參數(shù)為頁面的實例,可以通過它引用vuex中的變量
import Vue from 'vue'
module.exports = (vm) => {
// 初始化請求配置
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
})
// 請求攔截
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等字段
// 這里對res.result進(jìn)行返回,將會在this.$u.post(url).then(res => {})的then回調(diào)中的res的到
// 如果配置了originalData為true,請留意這里的返回值
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ù)錯誤', res);
}
return false;
}
} else {
uni.$u.toast('不能識別數(shù)據(jù)1')
return false;
}
}
return res
}, (res1) => {
/* 對響應(yīng)錯誤做點什么 (statusCode !== 200)*/
console.log(res1, '失敗')
if (res1.statusCode == 401) {
// 假設(shè)401為token失效,這里跳轉(zhuǎn)登錄
uni.$u.toast('請登錄后操作');
console.log(Vue.prototype.$store, 'Vue.prototype.$store');
Vue.prototype.$store.commit('SET_MEMBER', {})
setTimeout(() => {
// 此為uView的方法,詳見路由相關(guān)文檔
uni.$u.route({
url: '/pages/login/login',
})
}, 1500)
return res1.data;
} else {
uni.$u.toast('不能識別數(shù)據(jù)2');
// 如果返回false,則會調(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: [
// 可以有多個持久化實例
createPersistedState({
key: 'app_config_data', // 狀態(tài)保存到本地的 key
paths: ['member', 'cookieKey'], // 要持久化的狀態(tài),在state里面取,如果有嵌套,可以 a.b.c
storage: { // 存儲方式定義
getItem: (key) => uni.getStorageSync(key), // 獲取
setItem: (key, value) => uni.setStorageSync(key, value), // 存儲
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、接下來就是在頁面中發(fā)實際應(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ò)請求中data.data的數(shù)據(jù)

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

