大氣集團企業(yè)網(wǎng)站模板優(yōu)化排名 生客seo
文章目錄
- 1,通過命令行創(chuàng)建uniapp vue3 ts項目
- 2, 創(chuàng)建springboot后臺項目
- 3, 聯(lián)調(diào)測試
1,通過命令行創(chuàng)建uniapp vue3 ts項目
? 官方通過命令行創(chuàng)建項目的地址:https://zh.uniapp.dcloud.io/quickstart-cli.html
? 在執(zhí)行下面操作之前,請先保證已安裝node.js
。網(wǎng)址:https://nodejs.org/en
第一步:全局安裝vue-cli
,如果已經(jīng)安裝過,可以跳過次步驟
npm install -g @vue/cli
? 可以通過在命令行中輸入下面指令查看安裝后的版本
vue -V
第二步:創(chuàng)建以 typescript 開發(fā)的工程(如命令行創(chuàng)建失敗,請直接訪問 gitee 下載模板)
npx degit dcloudio/uni-preset-vue#vite-ts uni-vue3-project-one
第三步:用Visual Studio Code
打開上面創(chuàng)建的項目
第四步:在項目目錄執(zhí)行npm install
命令安裝相關(guān)依賴包
第五步:通過下面命令在頁面中啟動項目
npm run dev:h5
? 其他方式的啟動和打包指令可以在package.json
中查看。
第六步:通過頁面訪問
第七步:安裝uni
相關(guān)的插件
? 由于HbuilderX
對 TS
類型支持暫不完善,VS Code
對 TS
類型支持友好,同時這個編輯器也是大家熟悉的編譯器。在Visual Studio Code
中安裝下面三個插件。

第八步:安裝uni
的TS
支持類型
? 在執(zhí)行下面安裝方法之前,我們先將package.json
中的"typescript": "^4.9.4",
改成"typescript": "^5.0.0",
。修改完成后,執(zhí)行npm install
后在執(zhí)行下面操作。
npm install @types/wechat-miniprogram -D
npm install @uni-helper/uni-app-types -D
npm install @uni-helper/uni-ui-types -D
? 修改tsconfig.json
配置文件內(nèi)容如下:
{"extends": "@vue/tsconfig/tsconfig.json","compilerOptions": {"sourceMap": true,"baseUrl": ".","paths": {"@/*": ["./src/*"]},"lib": ["esnext", "dom"],"types": ["@dcloudio/types","@types/wechat-miniprogram","@uni-helper/uni-app-types","@uni-helper/uni-ui-types"],},"vueCompilerOptions": {"plugins": ["@uni-helper/uni-app-types/volar-plugin"],},"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
? 修改完成后,會看到下面報錯信息

? 打開@vue/tsconfig/tsconfig.json
文件,注釋下面兩行代碼:
// "preserveValueImports": true,// "importsNotUsedAsValues": "error",
第九步:編寫請求接口的相關(guān)內(nèi)容
? 在src
目錄下面新建utils
目錄,新建index.ts
,http.ts
兩個文件,代碼的內(nèi)容如下:
? index.ts
代碼內(nèi)容如下:
/*** 日期格式化函數(shù)* @param date 日期對象* @param format 日期格式,默認為 YYYY-MM-DD HH:mm:ss*/
export const formatDate = (date: Date, format = 'YYYY-MM-DD HH:mm:ss') => {// 獲取年月日時分秒,通過 padStart 補 0const year = String(date.getFullYear())const month = String(date.getMonth() + 1).padStart(2, '0')const day = String(date.getDate()).padStart(2, '0')const hours = String(date.getHours()).padStart(2, '0')const minutes = String(date.getMinutes()).padStart(2, '0')const seconds = String(date.getSeconds()).padStart(2, '0')const millSeconds = String(date.getMilliseconds())// 返回格式化后的結(jié)果return format.replace('YYYY', year).replace('MM', month).replace('DD', day).replace('HH', hours).replace('mm', minutes).replace('ss', seconds).replace('SSS',millSeconds)
}
? http.ts
代碼內(nèi)容如下:
import {formatDate} from "@/utils/index"const baseURL = '/api'/*** 后臺請求報文結(jié)構(gòu)*/
export class ComReq{requestTime: string;origin:string;data: any;constructor(requestTime: string,data: any){this.requestTime=requestTime;this.data=data;this.origin="H5";}
}/*** 后臺響應(yīng)報文結(jié)構(gòu)*/
export type ComResp<T>={reponseTime: string,code: string,msg: string,data: T
}// 添加攔截器
const httpInterceptor = {// 攔截前觸發(fā)invoke(options: UniApp.RequestOptions) {// 1. 非 http 開頭需拼接地址if (!options.url.startsWith('http')) {options.url = baseURL + options.url}// 2. 請求超時, 默認 60soptions.timeout = 30000// 3. 添加小程序端請求頭標識options.header = {...options.header,'source-client': 'H5',}// 4.統(tǒng)一封裝請求后臺數(shù)據(jù)結(jié)構(gòu)options.data=new ComReq(formatDate(new Date(),"YYYYMMDDHHmmssSSS"),options.data)},
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)// 2.2 添加類型,支持泛型
export const http = <T>(options: UniApp.RequestOptions) => {// 1. 返回 Promise 對象return new Promise<T>((resolve, reject) => {uni.request({...options,// 響應(yīng)成功success(res) {// 狀態(tài)碼 2xx, axios 就是這樣設(shè)計的if (res.statusCode >= 200 && res.statusCode < 300) {// 2.1 提取核心數(shù)據(jù) res.dataconst result=res.data as ComResp<T>if(result.code==='0000'){resolve(result.data)}else{uni.showToast({icon: 'none',title: result.msg || '接口響應(yīng)錯誤',})console.log(111)reject(res)}} else if (res.statusCode === 401) {// 401錯誤 -> 清理用戶信息,跳轉(zhuǎn)到登錄頁uni.navigateTo({ url: '/pages/login/login' })reject(res)} else {// 其他錯誤 -> 根據(jù)后端錯誤信息輕提示uni.showToast({icon: 'none',title: (res.data as ComResp<T>).msg || '請求錯誤',})reject(res)}},// 響應(yīng)失敗fail(err) {uni.showToast({icon: 'none',title: '網(wǎng)絡(luò)錯誤,換個網(wǎng)絡(luò)試試',})reject(err)},})})
}
第十步:編寫一個測試用的登錄接口
? 在src
目錄下面新建目錄types
,在該目錄下面建一個文件login.d.ts
用來定義登錄的請求和響應(yīng)類型,具體的代碼如下:
/*** 請求登錄類型*/
export type LoginReqDTO = {username: stringpassword: string
}/*** 登錄響應(yīng)類型*/
export type LoginRespDTO = {token: string
}
? 在src
目錄下面新建目錄api
,在該目錄下面新建文件login.ts
,具體的代碼類型如下:
import { LoginReqDTO,LoginRespDTO } from '@/types/login'
import { http } from '@/utils/http'export const loginByPwd = (data: LoginReqDTO) => {return http<LoginRespDTO>({method: 'POST',url: '/login',data,})
}
? 修改pages/index/index.vue
文件,在代碼中新增調(diào)用接口loginByPwd
的按鈕,具體的代碼邏輯如下:
<template><view class="content"><image mode="aspectFill" class="logo" src="/static/logo.png"/><view class="text-area" @tap="doLogin"><text class="title">點擊</text></view></view>
</template><script setup lang="ts">
import {loginByPwd} from "@/api/login"const doLogin=async()=>{const res=await loginByPwd({username:"dream21th",password:"123456"})console.log(res)
}
</script><style>
.content {display: flex;flex-direction: column;align-items: center;justify-content: center;
}.logo {height: 200rpx;width: 200rpx;margin-top: 200rpx;margin-left: auto;margin-right: auto;margin-bottom: 50rpx;
}.text-area {display: flex;justify-content: center;
}.title {font-size: 36rpx;color: #8f8f94;
}
</style>
? 修改vite.config.ts
文件,增加接口代理請求地址并允許跨域請求:
import { defineConfig } from "vite";
import uni from "@dcloudio/vite-plugin-uni";// https://vitejs.dev/config/
export default defineConfig({server:{//頁面默認打開open:true,//頁面打開端口port:8088,//代理請求地址proxy:{'/api':'http://127.0.0.1:8081'},//允許跨域請求cors: true},plugins: [uni()],
});
2, 創(chuàng)建springboot后臺項目
? springboot
項目初始化地址:https://start.spring.io/
? 本次構(gòu)建項目的參數(shù)選擇如下。創(chuàng)建項目完成后,用idea
導(dǎo)入項目。
第一步:在pom.xml
文件中增加下面的依賴
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency>
第二步:將application.properties
文件重命名為application.yml
,修改里面的內(nèi)容如下:
spring:application:name: project-one
server:port: 8081
第三步:編寫一些通用類,來完成接口的聯(lián)調(diào)
? 編寫com.dream21th.springboot.project.one.utils.Dates
類來獲取時間格式化數(shù)據(jù),具體的代碼實現(xiàn)如下:
package com.dream21th.springboot.project.one.utils;import java.time.*;
import java.time.format.DateTimeFormatter;public final class Dates {public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";/*** 得到當前時間,格式為yyyyMMddHHmmss** @return*/public static String getyyyyMMddHHmmssCurDate() {return LocalDateTime.now().format(DateTimeFormatter.ofPattern(YYYYMMDDHHMMSS));}
}
? 編寫響應(yīng)碼值的枚舉類com.dream21th.springboot.project.one.enums.ResultEnum
package com.dream21th.springboot.project.one.enums;/*** @Author dream21th* @Date 2024/12/28 10:20*/
public enum ResultEnum {SUCCESS("0000","SUCCESS"),ERROR("9999","ERROR");public final String code;public final String msg;ResultEnum(String code,String msg){this.code=code;this.msg=msg;}
}
? 編寫通用請求com.dream21th.springboot.project.one.dto.ComReq
和響應(yīng)類型com.dream21th.springboot.project.one.dto.ComResp
package com.dream21th.springboot.project.one.dto;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;/*** @Author dream21th* @Date 2024/12/28 10:41*/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class ComReq<T> {private String requestTime;private String requestNo;T data;
}
package com.dream21th.springboot.project.one.dto;import com.dream21th.springboot.project.one.enums.ResultEnum;
import com.dream21th.springboot.project.one.utils.Dates;
import lombok.Getter;/*** @Author dream21th* @Date 2024/12/28 10:04*/
@Getter
public class ComResp<T> {private String reponseTime;private String responseNo;private String code;private String msg;T data;public ComResp<T> responseNo(String responseNo){this.responseNo=responseNo;return this;}public ComResp<T> data(T data){this.data=data;return this;}public ComResp<T> success(){this.code= ResultEnum.SUCCESS.code;this.msg=ResultEnum.SUCCESS.msg;this.reponseTime= Dates.getyyyyMMddHHmmssCurDate();return this;}public ComResp<T> error(){this.code= ResultEnum.ERROR.code;this.msg=ResultEnum.ERROR.msg;this.reponseTime= Dates.getyyyyMMddHHmmssCurDate();return this;}public ComResp<T> error(ResultEnum resultEnum){this.code= resultEnum.code;this.msg=resultEnum.msg;this.reponseTime= Dates.getyyyyMMddHHmmssCurDate();return this;}
}
? 編寫登錄接口的請求和響應(yīng)結(jié)構(gòu)體
package com.dream21th.springboot.project.one.dto.login;import lombok.Data;/*** @Author dream21th* @Date 2024/12/28 13:28*/
@Data
public class LoginReqDTO {private String username;private String password;
}
package com.dream21th.springboot.project.one.dto.login;import lombok.Builder;
import lombok.Data;/*** @Author dream21th* @Date 2024/12/28 13:28*/
@Data
@Builder
public class LoginRespDTO {private String token;
}
第四步: 編寫登錄接口,具體的代碼實現(xiàn)如下(接口沒有具體的邏輯,只是接受前端的請求參數(shù),并返回一個token)
package com.dream21th.springboot.project.one.controller;import com.dream21th.springboot.project.one.dto.ComReq;
import com.dream21th.springboot.project.one.dto.ComResp;
import com.dream21th.springboot.project.one.dto.login.LoginReqDTO;
import com.dream21th.springboot.project.one.dto.login.LoginRespDTO;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.UUID;/*** @Author dream21th* @Date 2024/12/27 16:58*/
@RestController
@RequestMapping("/api")
public class LoginController {@PostMapping("/login")public ComResp<LoginRespDTO> login(@RequestBody ComReq<LoginReqDTO> comReq){return new ComResp<LoginRespDTO>().data(LoginRespDTO.builder().token(UUID.randomUUID().toString()).build()).responseNo(comReq.getRequestNo()).success();}
}
3, 聯(lián)調(diào)測試
? 分別啟動前端項目和后臺項目,打開頁面http://localhost:8088/
,點擊按鈕
? 發(fā)現(xiàn)接口調(diào)用成功。到此一個示例uniapp
和springboot
項目搭建完成。