基础架构
前言:这两天在学习小兔鲜儿微信小程序项目,想要实现微信小程序的开发,首先就要搭建基础框架了,希望我的文章可以帮助大家快速上手微信小程序
构建界面
引入 uni-ui 组件库
uni-ui是uni-app官方出品,不仅使用安全且支持多端
uni-ui支持 HBuilderX直接新建项目模板、npm安装和单独导入个别组件等多种使用方式
安装 uni-ui
pnpm i @dcloudio/uni-ui
组件自动引入
配置easycom
使用npm安装好uni-ui之后,需要配置easycom规则,让npm安装的组件支持easycom
打开项目根目录下的pages.json并添加easycom节点:
// pages.json
{ \"easycom\": { \"autoscan\": true, \"custom\": { // uni-ui 规则如下配置 \"^uni-(.*)\": \"@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue\" } }, // 其他内容 pages:[ // ... ]
}
配置TS类型
- @uni-helper/uni-app-types提供uni-app组件类型
- @uni-helper/uni-cloud-types提供uni-cloud组件类型
- @uni-helper/uni-ui-types(当前仓库)提供uni-ui组件类型
基于这个 PR,Vue Language Features (Volar)已经支持。
安装之后,建议启用接管模式 Takeover Mode。如果不想启用接管模式,可以安装TypeScript Vue Plugin (Volar)。启用或安装后需要重启 VSCode。
安装依赖
pnpm i -D @uni-helper/uni-ui-types
配置tsconfig.json,确保compilerOptions.types中含有@dcloudio/types和@uni-helper/uni-ui-types且include包含了对应的vue文件
// tsconfig.json
{
\"compilerOptions\": {
\"types\": [\"@dcloudio/types\",
\"miniprogram-api-typings\",
\"@uni-helper/uni-app-types\",
\"@uni-helper/uni-ui-types\"]
},
}
状态管理
持久化
// 网页端API localStorage.setItem() localStorage.getItem()
// 兼容多端API uni.setStorageSync() uni.getStorageSync()
数据交互
请求工具
请求和上传文件拦截器
uni.addInterceptor(STRING, OBJECT)
添加拦截器
STRING 参数说明
需要拦截的api名称,如:uni.addInterceptor(\’request\’, OBJECT),将拦截uni.request()
注意:
- 仅支持异步接口,如:uni.setStorage(OBJECT),暂不支持同步接口如uni.setStorageSync(KEY,DATA)
-
uniCloud请求云端接口时(callFunction、uploadFile等)也会使用uni.request发送请求,请确保拦截器内不错误的处理此类请求
// 拦截 request 请求 uni.addInterceptor(\'request\', httpInterceptor) // 拦截 uploadFile 文件上传 uni.addInterceptor(\'uploadFile\', httpInterceptor)
const httpInterceptor = {
// 拦截前触发
invoke(options: UniApp.RequestOptions) {
// 1. 非 http 开头需拼接地址
if (!options.url.startsWith(\'http\')) {
options.url = baseURL + options.url
}
// 2. 请求超时
options.timeout = 10000
// 3. 添加小程序端请求头标识
options.header = {
...options.header,
\'source-client\': \'miniapp\',
}
// 4. 添加 token 请求头标识
const memberStore = useMemberStore()
const token = memberStore.profile?.token
if (token) {
options.header.Authorization = token
}
}
}
封装 Promise 请求函数
请求成功提取数据和设置类型
获取数据失败
? uni.request 的 success 回调函数只是表示服务器 响应成功 , 没处理响应状态码 ,业务中使用不方便
? axios 函数是只有 响应状态码是 2xx 才调用 resolve 函数,表示获取数据成功 ,业务中使用更准确
来源:https://blog.csdn.net/weixin_73295475/article/details/132916145
