前端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 } } // #endif
5、接下來(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)擊這里:www.dbjr.com.cn/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)文章
淺談Vue3.0之前你必須知道的TypeScript實(shí)戰(zhàn)技巧
這篇文章主要介紹了淺談Vue3.0之前你必須知道的TypeScript實(shí)戰(zhàn)技巧,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09JavaScript中的類(lèi)(Class)詳細(xì)介紹
這篇文章主要介紹了JavaScript中的類(lèi)(Class)詳細(xì)介紹,本文講解了JavaScript中類(lèi)的定義、JavaScript中的Constructor(構(gòu)造函數(shù))、類(lèi)名等內(nèi)容,需要的朋友可以參考下2014-12-12js實(shí)現(xiàn)整體縮放頁(yè)面適配移動(dòng)端
這篇文章主要介紹了js實(shí)現(xiàn)整體縮放頁(yè)面適配移動(dòng)端,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03利用jsPDF實(shí)現(xiàn)將圖片轉(zhuǎn)為pdf
這篇文章主要為大家詳細(xì)介紹了如何利用jsPDF實(shí)現(xiàn)將圖片轉(zhuǎn)為pdf的功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-08-08JS編寫(xiě)函數(shù)實(shí)現(xiàn)對(duì)身份證號(hào)碼最后一位的驗(yàn)證功能
二代身份證號(hào)碼為18位,怎么編寫(xiě)函數(shù)實(shí)現(xiàn)對(duì)身份證號(hào)碼最后一位的驗(yàn)證功能呢?今天小編通過(guò)代碼給大家分享下實(shí)現(xiàn)方法2016-12-12合并多個(gè)ArrayBuffer場(chǎng)景及方法示例
這篇文章主要為大家介紹了合并多個(gè)ArrayBuffer方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11JavaScript中最容易混淆的作用域、提升、閉包知識(shí)詳解(推薦)
在web前端開(kāi)發(fā)中js中的作用域,提升,閉包知識(shí)是經(jīng)常用到的也是很容易混淆的知識(shí)點(diǎn),接下來(lái)小編整理了本教程幫助大家學(xué)習(xí)2016-09-09