前端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)一放進對象掛載到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 為默認全局配置*/ 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進行返回,將會在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), // 并將進入this.$u.post(url).then().catch(res=>{})的catch回調(diào)中,res為服務(wù)端的返回值 return false; } return Promise.reject(res) }) }
3、全局數(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', // 默認地為你為北京地址 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、接下來就是在頁面中發(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的詳細使用可以點擊這里:chabaoo.cn/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)文章
淺談Vue3.0之前你必須知道的TypeScript實戰(zhàn)技巧
這篇文章主要介紹了淺談Vue3.0之前你必須知道的TypeScript實戰(zhàn)技巧,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09利用jsPDF實現(xiàn)將圖片轉(zhuǎn)為pdf
這篇文章主要為大家詳細介紹了如何利用jsPDF實現(xiàn)將圖片轉(zhuǎn)為pdf的功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下2023-08-08JS編寫函數(shù)實現(xiàn)對身份證號碼最后一位的驗證功能
二代身份證號碼為18位,怎么編寫函數(shù)實現(xiàn)對身份證號碼最后一位的驗證功能呢?今天小編通過代碼給大家分享下實現(xiàn)方法2016-12-12JavaScript中最容易混淆的作用域、提升、閉包知識詳解(推薦)
在web前端開發(fā)中js中的作用域,提升,閉包知識是經(jīng)常用到的也是很容易混淆的知識點,接下來小編整理了本教程幫助大家學(xué)習(xí)2016-09-09