結(jié)合上一篇Axiso接口封裝,使用uni-app快速搭建小程序、H5框架(uniapp接口對接)

現(xiàn)在我們來快速搭建一個開箱即用的小程序、H5開發(fā)框架 (vue3 ts)

一、我們先來快速預(yù)覽一下我們的框架結(jié)構(gòu)

結(jié)合上一篇Axiso接口封裝,使用uni-app快速搭建小程序、H5框架(uniapp接口對接)

二、使用以下命令快速創(chuàng)建項目

npx degit dcloudio/uni-preset-vue#vite-ts my-vue3-project //或者直接下載https://gitee.com/dcloud/uni-preset-vue/repository/archive/vite-ts.zip

三、首先處理全局配置和axiso封裝

在src下創(chuàng)建utils 、config文件,(注意:我們把上述的 api 文件移入utils)

1、首先在我們創(chuàng)建的 config 文件下面創(chuàng)建 app.ts 文件,為方便復(fù)制代碼如下:

export const APP_NAME = '開箱及用小程序、H5'export const IMAGE_URL = 'xxxxx' // 靜態(tài)資源的地址export const HTTP_Request_URL = 'xxxxx'export const header = { 'content-type': 'application/json',}export const HEADERPARAMS = { 'content-type': 'application/x-www-form-urlencoded',}export const TOKENNAME = 'Authorization'

2、接下來創(chuàng)建 requestClass.ts 文件,代碼如下

const config = Symbol('config')const isCompleteURL = Symbol('isCompleteURL')const requestBefore = Symbol('requestBefore')const requestAfter = Symbol('requestAfter')class requestClass { // 默認(rèn)配置 [config]: { baseURL?: string } & UniApp.RequestOptions = { baseURL: '', url: '', HEADER: { 'content-type': 'application/x-www-form-urlencoded', }, method: 'GET', timeout: 3000, dataType: 'json', responseType: 'text' } // 攔截器 interceptors = { request: (func: Fn) => { if (func) { requestClass[requestBefore] = func } else { requestClass[requestBefore] = (request) => request } }, response: (func: Fn) => { if (func) { requestClass[requestAfter] = func } else { requestClass[requestAfter] = (response) => response } }, } static [requestBefore](config: UniApp.RequestOptions) { Return config } static [requestAfter](response: any) { return response } static [isCompleteURL](url: string) { return /(http|https)://([w.] /?)S*/.test(url) } request(options: UniApp.RequestOptions & { baseURL?: string }) { options.baseURL = options.baseURL || this[config].baseURL options.dataType = options.dataType || this[config].dataType options.url = requestClass[isCompleteURL](options.url) ? options.url : (options.baseURL options.url) options.data = options.data options.header = { ...options.header, ...this[config].header } options.method = options.method || this[config].method options = { ...options, ...requestClass[requestBefore](options) } return new Promise((resolve, reject) => { options.success = function (res) { resolve(requestClass[requestAfter](res)) } options.fail = function (err) { reject(requestClass[requestAfter](err)) } uni.request(options) let obj: any = {} obj[request.url] = uni.request(options) abortRequest() { for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { const element = obj[key]; element.abort() } } } }) } get(url: string, data: any = {}, options: Recordable = {}) { return this.request({ ...options, url, data, method: 'GET' }) } post(url: string, data: any = {}, options: Recordable = {}) { return this.request({ ...options, url, data, method: 'POST' }) } put(url: string, data: any = {}, options: Recordable = {}) { return this.request({ ...options, url, data, method: 'PUT' }) } delete(url: string, data: any = {}, options: Recordable = {}) { return this.request({ ...options, url, data, method: 'DELETE' }) } getConfig() { return this[config] } // 修改默認(rèn)配置的一個方法,可以修改請求地址,請求方式等等.. setConfig(func: Fn) { this[config] = func(this[config]) }}export default requestClass

3、下面創(chuàng)建 request.ts,代碼如下

import requestClass from './requestClass'import { HEADER, HEADERPARAMS, TOKENNAME, HTTP_REQUEST_URL } from '@/config/app'import qs from 'qs'const Request = new requestClass()// 請求攔截器Request.interceptors.request((request: any) => { if (request.header.contentType) { request.header['content-type'] = request.header.contentType delete request.header.contentType } if (request.method === 'GET') { request.data = qs.stringify(request.data) request.url = request.url '?' request.data } return request})// 響應(yīng)攔截器Request.interceptors.response((response: any) => { const token = uni.getStorageSync('userDate').token // if (response.data.code === 403) { // uni.showToast({ // title: token ? '請重新登錄' : '請先登錄', // icon: 'none', // duration: 2000, // }) // uni.removeStorageSync('token') // uni.removeStorageSync('userInfo') // } return response})// 設(shè)置默認(rèn)配置Request.setConfig((config: any) => { config.baseURL = HTTP_REQUEST_URL if (uni.getStorageSync('userDate').token) { config.header['Authorization'] = 'Bearer ' uni.getStorageSync('token') config.header['token'] = uni.getStorageSync('userDate').token } return config})export default Request

4、最后我們創(chuàng)建我們的 api.ts, 代碼如下

import request from '@/utils/request'const options = { header: { 'content-type': 'application/x-www-form-urlencoded'}, token: uni.getStorageSync('userDate').token}/** * @method 測試接口 */export function testGet(data :any) { return request.get('/api/kecheng/getchargekechenginfo', data)}export function testPost(data :any) { return request.post('/api/kecheng/getlistsuddenstudy', data, options)}export function testPut(data :any) { return request.post('/testPut', data)}export function testDelete(data :any) { return request.delete('/testDelete', data)}

四、處理我們的vuex,在src下創(chuàng)建store文件(在store 下創(chuàng)建 index.ts 、gettres.ts 和modules文件夾)

1、index.ts,代碼如下

import { InjectionKey} from 'vue'import { createStore } from 'vuex'import { store as app, Appstate, AppStore } from '@/store/modules/app'import getters from './getters'export const key: InjectionKey<Store> = Symbol()export interface RootState { app: AppState}export type Store = AppStore<Pick<RootState, 'app'>>export const store = createStore<RootState>({ modules: { app }, getters})export function useStore(): Store { return store as Store}

2、gettres.ts,代碼如下

import { RootState } from '@/store'export default { token: (state: RootState) => state.app.token,}

3、在modules 下創(chuàng)建app文件夾(在 app 文件夾創(chuàng)建以下文件夾)

1、index.ts,代碼如下:

import { Store as VuexStore, CommitOptions, DispatchOptions, Module } from 'vuex'import { RootState } from '@/store'import { state } from './state'import { actions, Actions } from './actions'import { mutations, Mutations } from './mutations'import type { AppState } from './state'export { AppState }export type AppStore<S = AppState> = Omit<VuexStore<S>, 'getters' | 'commit' | 'dispatch'> & { commit<K extends keyof Mutations, P extends Parameters<Mutations[K]>[1]>( key: K, payload: P, options?: CommitOptions ): ReturnType<Mutations[K]>} & { dispatch<K extends keyof Actions>( key: K, payload: Parameters<Actions[K]>[1], options?: DispatchOptions ): ReturnType<Actions[K]>}export const store: Module<AppState, RootState> = { state, actions, mutations,}

2、state.ts,代碼如下:

import {reactive} from 'vue'export interface AppState { token: string, userData: object}export const state: AppState = reactive({ token: '', userData:[]})

3、mutations.ts,代碼如下:

import { MutationTree } from 'vuex'import { AppState } from './state'import { AppMutationTypes } from './mutation-types'export type Mutations<S = AppState> = { // [AppMutationTypes.SET_TOKEN](state: S, token: string): void}export const mutations: MutationTree<AppState> & Mutations = { [AppMutationTypes.SET_USER_MSG](state: AppState, userData: object) { state.userData = userData }}

4、mutation-types.ts,代碼如下:

export enum AppMutationTypes { SET_USER_MSG = 'SET_USER_MSG', //SET_TOKEN = 'SET_TOKEN',}

5、actions.ts,代碼如下:

import { ActionTree, ActionContext } from 'vuex'import { RootState } from '@/store'import { AppState } from './state'import { Mutations } from './mutations'import { AppActionTypes } from './action-types'import { AppMutationTypes } from './mutation-types'type AugmentedActionContext = { commit<K extends keyof Mutations>(key: K, payload: Parameters<Mutations[K]>[1]): ReturnType<Mutations[K]>} & Omit<ActionContext<AppState, RootState>, 'commit'>export interface Actions { // [AppActionTypes.ACTION_RESET_TOKEN]({ commit }: AugmentedActionContext): void}export const actions: ActionTree<AppState, RootState> & Actions = { [AppActionTypes.ACTION_LOGIN]({ commit }: AugmentedActionContext, userData: object) { commit(AppMutationTypes.SET_USER_MSG, userData) }, // [AppActionTypes.ACTION_RESET_TOKEN]({ commit }: AugmentedActionContext) { // commit(AppMutationTypes.SET_TOKEN, '') // }}

6、action-types.ts,代碼如下:

export enum AppActionTypes { ACTION_LOGIN = 'ACTION_LOGIN', ACTION_RESET_TOKEN = 'ACTION_RESET_TOKEN',}

五、其他配置

1、main.ts ( 小程序默認(rèn)頂部狀態(tài)欄高度處理,全局變量配置等)

import { createSSRApp } from 'vue'import App from './App.vue'import { store } from './store'export function createApp() { const app = createSSRApp(App) //獲取頂部狀態(tài)欄高度uni.getSystemInfo({ success: function (e: any) { // #ifndef MP app.config.globalProperties.$StatusBar = e.statusBarHeight if (e.platform == 'android') { app.config.globalProperties.$CustomBar = e.statusBarHeight 50 } else { app.config.globalProperties.$CustomBar = e.statusBarHeight 45 } // #endif // #ifdef MP-WEIXIN app.config.globalProperties.$StatusBar = e.statusBarHeight const custom = wx.getMenuButtonBoundingClientRect() app.config.globalProperties.$Custom = custom app.config.globalProperties.$CustomBar = custom.bottom custom.top - e.statusBarHeight // #endif //窗口高度 app.config.globalProperties.$windowHeight = e.windowHeight //獲取導(dǎo)航高度 app.config.globalProperties.$navHeight = e.statusBarHeight * (750 / e.windowWidth) 91 app.config.globalProperties.$SystemInfo = e }, }) app.use(store) return { app, }}

2、小程序分包(pages.json) 例如(根據(jù)需要刪減,但保持結(jié)構(gòu)不變)

{ "pages": [ //pages數(shù)組中第一項表示應(yīng)用啟動頁,參考:https://uniapp.dcloud.io/collocation/pages { "path": "pages/template/index", "style": { "navigationBarTitleText": "開箱及用小程序、H5", "navigationStyle": "custom" } }, { "path": "pages/template/settled", "style": { "navigationBarTitleText": "開箱及用小程序、H5", "navigationBarTextStyle": "black", "navigationBarBackgroundColor": "#fff", "backgroundColor": "#f7f7f7" } }, { "path": "pages/template/user", "style": { "navigationBarTitleText": "開箱及用小程序、H5", "navigationBarTextStyle": "black", "navigationBarBackgroundColor": "#fff", "backgroundColor": "#f7f7f7" } } ], //分包 "subPackages": [ { "root":"pages/teachers", "pages":[{ "path":"teacherdetail", "style": { "navigationBarTitleText": "開箱及用小程序、H5", "navigationBarTextStyle": "black", "navigationBarBackgroundColor": "#fff", "backgroundColor": "#f7f7f7" } }] },{ "root":"pages/user", "pages":[{ "path":"collection", "style": { "navigationBarTitleText": "開箱及用小程序、H5", "navigationBarTextStyle": "black", "navigationBarBackgroundColor": "#fff", "backgroundColor": "#f7f7f7" } },{ "path":"appointment", "style": { "navigationBarTitleText": "開箱及用小程序、H5", "navigationBarTextStyle": "black", "navigationBarBackgroundColor": "#fff", "backgroundColor": "#f7f7f7" } }] }], "tabBar": { "color": "#7a7e83", "selectedColor": "#1296db", "backgroundColor": "#ffffff", "list": [{ "pagePath": "pages/template/index", "text": "首頁", "iconPath": "static/img/index.png", "selectedIconPath": "static/img/index_ed.png" }, { "pagePath": "pages/template/settled", "text": "你的", "iconPath": "static/img/learn.png", "selectedIconPath": "static/img/learn_ed.png" }, { "pagePath": "pages/template/user", "text": "我的", "iconPath": "static/img/user.png", "selectedIconPath": "static/img/user_ed.png" }] }, "globalStyle": { "navigationBarTextStyle": "black", "navigationBarTitleText": "uni-app", "navigationBarBackgroundColor": "#F8F8F8", "backgroundColor": "#F8F8F8" }}

2、注意封裝接口的引入和vuex的使用,例如

1、接口調(diào)用

結(jié)合上一篇Axiso接口封裝,使用uni-app快速搭建小程序、H5框架(uniapp接口對接)

//例如在頁面引入 三 4 下面的 testPost方法import { testPost} from '@/utils/index'//使用const data = { 'token':'23232321121', 'workType':1}testPost(data).then((res:any):void => { console.log(state.workTypeList )}).catch((err) => {})

2、vuex調(diào)用

注意:vue3調(diào)用狀態(tài)管理和Vue2不同(三步走)

結(jié)合上一篇Axiso接口封裝,使用uni-app快速搭建小程序、H5框架(uniapp接口對接)

//引入 useStoreimport { useStore } from 'vuex'//調(diào)用const store = useStore()//通過 store 調(diào)用 actions 我們的用戶登錄方法store.dispatch(AppActionTypes.ACTION_LOGIN, xxx)

最后我們看一下vue3 setup() 方法,我們可能看到兩種不同的寫法

//個人推薦組件封裝使用這種<script lang="ts"> import {defineComponent} from 'vue' export default defineComponent({ name: "xxx", setup(props, context){ } })</script>

<script setup lang="ts"> //引入 useStore import { useStore } from 'vuex' //調(diào)用 const store = useStore() //通過 store 調(diào)用 actions 我們的用戶登錄方法 store.dispatch(AppActionTypes.ACTION_LOGIN, xxx)</script>

接下來我們就可以快速開始我們的開發(fā)了

版權(quán)聲明:本文內(nèi)容由互聯(lián)網(wǎng)用戶自發(fā)貢獻(xiàn),該文觀點僅代表作者本人。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如發(fā)現(xiàn)本站有涉嫌抄襲侵權(quán)/違法違規(guī)的內(nèi)容, 請發(fā)送郵件至 舉報,一經(jīng)查實,本站將立刻刪除。

(0)
上一篇 2024年5月11日 下午2:13
下一篇 2024年5月11日 下午2:25

相關(guān)推薦

  • 財政部公布2024年1月至2月主要稅收收入項目、支出科目情況(財政部國稅總局2021年24號公告)

    央視網(wǎng)消息:財政部公布,2024年1—2月財政收支情況。 一、全國一般公共預(yù)算收支情況 (一)一般公共預(yù)算收入情況。 1—2月,全國一般公共預(yù)算收入44585億元,同比下降2.3%…

    科研百科 2024年4月21日
    72
  • 重大科研項目及成果較少

    重大科研項目及成果較少 近年來,隨著科技的不斷發(fā)展,許多重大科研項目正在不斷推進(jìn)。這些項目涉及到許多前沿領(lǐng)域,如人工智能、量子計算、生物技術(shù)等等。然而,在這些項目中,有些成果可能并…

    科研百科 2025年4月25日
    3
  • ae2022下載

    ae2022下載:掌握數(shù)字藝術(shù)的關(guān)鍵軟件 隨著數(shù)字藝術(shù)的不斷發(fā)展,使用Ae(Advanced Effects) 2022軟件已經(jīng)成為了數(shù)字藝術(shù)學(xué)習(xí)者和創(chuàng)作者的必備工具。Ae 202…

    科研百科 2024年11月6日
    5
  • 系統(tǒng)項目管理專業(yè)排名

    系統(tǒng)項目管理專業(yè)排名 系統(tǒng)項目管理是一個非常重要的專業(yè),能夠幫助企業(yè)高效地規(guī)劃和實施系統(tǒng)項目。隨著信息技術(shù)的不斷發(fā)展,系統(tǒng)項目管理的重要性也在不斷提升。以下是系統(tǒng)項目管理專業(yè)排名的…

    科研百科 2025年6月21日
    0
  • 如何做好項目進(jìn)度管理

    項目進(jìn)度管理是項目管理中至關(guān)重要的一環(huán),能夠幫助項目團(tuán)隊有效地控制項目進(jìn)度,確保項目按時完成,并達(dá)到預(yù)期目標(biāo)。本文將介紹如何做好項目進(jìn)度管理。 項目進(jìn)度管理包括對項目進(jìn)度的規(guī)劃和監(jiān)…

    科研百科 2024年8月18日
    2
  • 工程項目 管理系統(tǒng)

    工程項目管理系統(tǒng):提升項目管理效率 隨著工程項目的不斷增長,傳統(tǒng)的手動管理方式已經(jīng)無法滿足高效的項目管理需求。因此,工程項目管理系統(tǒng)應(yīng)運而生,它可以有效提高項目管理的效率和質(zhì)量。本…

    科研百科 2024年12月16日
    2
  • 文科科研項目中途退出

    文科科研項目中途退出 近年來,隨著科技的不斷進(jìn)步,文科科研項目也在不斷發(fā)展壯大。然而,在這個過程中,也出現(xiàn)了一些令人擔(dān)憂的問題。有些文科科研項目在開始階段就存在著各種各樣的問題,從…

    科研百科 2025年4月8日
    3
  • 湖南省新公司網(wǎng)上稅務(wù)登記操作流程

    湖南省新公司網(wǎng)上稅務(wù)登記操作流程 隨著電子商務(wù)的興起,越來越多的公司選擇在湖南省成立。但是,成立公司后,需要進(jìn)行稅務(wù)登記,才能合法地經(jīng)營。現(xiàn)在,湖南省的新公司可以通過網(wǎng)上稅務(wù)登記完…

    科研百科 2024年11月9日
    81
  • 科研項目的成果應(yīng)用

    科研項目的成果應(yīng)用 隨著科技的不斷進(jìn)步,科研項目的成果應(yīng)用也越來越廣泛。科研項目的成果應(yīng)用不僅可以幫助我們更好地理解自然世界,還可以推動人類社會的發(fā)展。本文將介紹一些科研項目的成果…

    科研百科 2025年3月26日
    12
  • 科研項目大綱范本

    科研項目大綱范本 科研項目大綱范本 科研項目大綱范本 科研項目大綱范本 科研項目大綱范本 科研項目大綱范本 科研項目大綱范本 科研項目大綱范本 科研項目大綱范本 科研項目大綱范本 …

    科研百科 2025年2月28日
    4
日韩国产一区二区| 在线精品91青草国产在线观看| 中文字幕在线久热精品| 日产2021乱码一区| 久久久久久夜精品精品免费啦| 手机在线看片国产| 中文字幕精品无码亚洲字| 巨胸喷奶水www视频网站| 七次郎在线视频精品视频| 天天爱天天做天天爽夜夜揉| mm131美女爽爽爽作爱视频| 在线亚洲人成电影网站色www| A∨变态另类天堂无码专区| 国产精品毛片无遮挡高清| 91成人午夜在线精品| 国产精品99在线观看| 香蕉视频在线看| 国产在线视频区| 美女和男生一起差差差| 午夜网站免费版在线观看| 特级毛片在线大全免费播放| 亚洲综合色丁香麻豆| 欧美国产日韩911在线观看| 亚洲午夜成人片| 日本高清天码一区在线播放| 久久久无码精品亚洲日韩蜜桃| 成人αv在线视频高清| 一本一本久久a久久精品综合麻豆 一本一本久久a久久精品综合麻豆 | 久久不见久久见免费影院www日本| 影音先锋女人aa鲁色资源| 一区二区三区在线观看免费 | 亚洲黄色片网站| 欧美一区二区三区四区视频| 亚洲avav天堂av在线网爱情| 无码日韩精品一区二区免费| 中文字幕aⅴ人妻一区二区| 天堂资源bt在线官网| 91福利免费体验区观看区| 国产成a人亚洲精v品无码| 精品成人AV一区二区三区| 免费a级毛片网站|