This commit is contained in:
yin 2026-09-18 18:38:29 +08:00
parent 428ae0ae34
commit 6ea0718371
31 changed files with 2286 additions and 4924 deletions

8
.env.development Normal file
View File

@ -0,0 +1,8 @@
# 开发环境配置
# uni-app(Vite)会自动按 mode 加载本文件,仅 VITE_ 前缀的变量会注入客户端
# 通过 import.meta.env.VITE_APP_BASE_API 读取
# 接口根地址(与 new3 Web 管理端开发环境指向同一后端,便于对照联调)
# 注意:小程序真机与线上由微信服务端校验域名白名单且必须 HTTPS,
# 本地联调依赖 manifest.json → mp-weixin.setting.urlCheck = false(仅影响开发者工具)
VITE_APP_BASE_API = 'http://192.168.11.56:6060/'

6
.env.production Normal file
View File

@ -0,0 +1,6 @@
# 生产环境配置
# 接口根地址
# ⚠️ 上线前必须替换为正式域名,并在「微信公众平台 → 开发管理 → 开发设置 → 服务器域名」
# 把该域名加入 request 合法域名白名单(必须 HTTPS、证书有效,不能是 IP 或非标准端口)
VITE_APP_BASE_API = 'https://qimen.wms.gztbyc.com/'

4941
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -55,6 +55,7 @@
"@dcloudio/uni-quickapp-webview": "3.0.0-5020420260813003",
"clipboard": "^2.0.11",
"dayjs": "^1.11.23",
"pinia": "^2.1.7",
"uview-plus": "^3.8.125",
"vue": "^3.4.21",
"vue-i18n": "^9.1.9"

10
shims-uni.d.ts vendored
View File

@ -1,10 +0,0 @@
/// <reference types='@dcloudio/types' />
import 'vue'
declare module '@vue/runtime-core' {
type Hooks = App.AppInstance & Page.PageInstance;
interface ComponentCustomOptions extends Hooks {
}
}

View File

@ -1,7 +1,11 @@
<script setup lang="ts">
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import { setupAuthGuard } from "@/utils/auth-guard";
onLaunch(() => {
console.log("App Launch");
// 注册全局跳转拦截:未登录时任何页面跳转都会被拦到登录页
// 等价于 new3(Web 端)在 router.beforeEach 里做的登录准入
setupAuthGuard();
});
onShow(() => {
console.log("App Show");

2
src/api/.gitkeep Normal file
View File

@ -0,0 +1,2 @@
接口层:按业务模块拆分的接口定义
request.ts 为请求实例(拦截器 / 统一错误处理),见开发清单第 5 节

95
src/api/user/user.ts Normal file
View File

@ -0,0 +1,95 @@
/**
* 用户相关接口(登录 / 注册 / 用户信息 / 退出)
*
* 与 new3(Web 端)的 `src/api/user/user.ts` 保持一致:
* 所有请求都打到同一个 /system 网关,业务方法由 query 的 `method` 指定。
*/
import request from '@/utils/request'
import type { BizResponse } from '@/utils/request'
/** /system 网关统一入口 */
const SYSTEM_URL = '/system'
/**
* 构造 /system 网关的公共 query 参数
* 与 new3 完全一致:method + v + timestamp
*/
function gatewayParams(method: string): Record<string, any> {
return { method, v: '1.0', timestamp: Date.now() }
}
// ────────────────────────────── 类型 ──────────────────────────────
/** 账号密码登录入参 */
export interface UserLoginParams {
username: string
password: string
/** 端标记,后端用于区分会话来源(小程序端固定 mobile) */
device?: string
}
/** 注册入参(字段与 new3 一致) */
export interface UserRegisterParams {
username: string
email: string
real_name: string
password: string
}
export interface UserLoginResult {
token: string
[key: string]: any
}
/** 用户信息:后端字段随业务扩展,此处只声明稳定字段,其余用索引签名兜住 */
export interface UserInfoResult {
employees_id?: number
employees_name?: string
permissions?: string[]
/** 后端菜单树,供后续「页面渲染框架」生成路由使用 */
menus?: any[]
[key: string]: any
}
// ────────────────────────────── 接口 ──────────────────────────────
/** 账号密码登录 */
export function login(data: UserLoginParams): Promise<BizResponse<UserLoginResult>> {
return request<UserLoginResult>({
url: SYSTEM_URL,
method: 'POST',
params: gatewayParams('user.login'),
data
})
}
/** 注册账号(注册成功后需再登录,与 new3 行为一致) */
export function register(data: UserRegisterParams): Promise<BizResponse<any>> {
return request({
url: SYSTEM_URL,
method: 'POST',
params: gatewayParams('user.register'),
data
})
}
/** 获取用户信息(含权限点与菜单) */
export function getInfo(data: Record<string, any> = {}): Promise<BizResponse<UserInfoResult>> {
return request<UserInfoResult>({
url: SYSTEM_URL,
method: 'POST',
params: gatewayParams('user.info'),
data
})
}
/** 退出登录 */
export function logout(data: Record<string, any> = {}): Promise<BizResponse<any>> {
return request({
url: SYSTEM_URL,
method: 'POST',
params: gatewayParams('user.logout'),
data
})
}

2
src/components/.gitkeep Normal file
View File

@ -0,0 +1,2 @@
全局自定义组件:easycom 自动扫描
注意:必须符合「组件名/组件名.vue」目录结构才会被扫描到,页面中无需 import

View File

@ -0,0 +1,399 @@
<template>
<view class="login-panel">
<!-- ── 品牌区 ── -->
<view class="login-panel__brand">
<view class="login-panel__logo">
<image v-if="logo" class="login-panel__logo-img" :src="logo" mode="aspectFit"></image>
<up-icon v-else name="server-man" color="#ffffff" size="46"></up-icon>
</view>
<text class="login-panel__brand-title">{{ title }}</text>
<text class="login-panel__brand-desc">{{ desc }}</text>
</view>
<!-- ── 表单卡片 ── -->
<view class="login-panel__card">
<view class="login-panel__head">
<text class="login-panel__head-title">{{ isRegister ? '注册账号' : '账号登录' }}</text>
<text class="login-panel__head-sub">
{{ isRegister ? '开启您的管理之旅' : '欢迎回来,请登录您的账户' }}
</text>
</view>
<!-- ========== 注册表单 ========== -->
<up-form
v-if="isRegister"
ref="registerFormRef"
:model="registerForm"
:rules="registerRules"
labelPosition="top"
>
<up-form-item label="账号" prop="username" required>
<up-input
v-model="registerForm.username"
placeholder="请输入账号"
prefixIcon="account"
clearable
maxlength="30"
></up-input>
</up-form-item>
<up-form-item label="邮箱" prop="email">
<up-input
v-model="registerForm.email"
placeholder="请输入邮箱"
prefixIcon="email"
clearable
maxlength="50"
></up-input>
</up-form-item>
<up-form-item label="姓名" prop="real_name">
<up-input
v-model="registerForm.real_name"
placeholder="请输入真实姓名"
prefixIcon="account-fill"
clearable
maxlength="20"
></up-input>
</up-form-item>
<up-form-item label="密码" prop="password" required>
<up-input
v-model="registerForm.password"
type="password"
placeholder="请输入密码(不少于 6 位)"
prefixIcon="lock"
clearable
maxlength="30"
></up-input>
</up-form-item>
<up-form-item label="确认密码" prop="confirmPassword" required>
<up-input
v-model="registerForm.confirmPassword"
type="password"
placeholder="请再次输入密码"
prefixIcon="lock"
clearable
maxlength="30"
@confirm="handleRegister"
></up-input>
</up-form-item>
<view class="login-panel__submit">
<up-button
type="primary"
shape="circle"
:loading="loading"
:text="loading ? '注册中...' : '注 册'"
@click="handleRegister"
></up-button>
</view>
<view class="login-panel__foot">
<text class="login-panel__foot-text">已有账号?</text>
<text class="login-panel__link" @click="switchMode(false)">立即登录</text>
</view>
</up-form>
<!-- ========== 登录表单 ========== -->
<up-form
v-else
ref="loginFormRef"
:model="loginForm"
:rules="loginRules"
labelPosition="top"
>
<up-form-item label="账号" prop="username" required>
<up-input
v-model="loginForm.username"
placeholder="请输入账号"
prefixIcon="account"
clearable
maxlength="30"
></up-input>
</up-form-item>
<up-form-item label="密码" prop="password" required>
<up-input
v-model="loginForm.password"
type="password"
placeholder="请输入密码"
prefixIcon="lock"
clearable
maxlength="30"
@confirm="handleLogin"
></up-input>
</up-form-item>
<view class="login-panel__submit">
<up-button
type="primary"
shape="circle"
:loading="loading"
:text="loading ? '登录中...' : '登 录'"
@click="handleLogin"
></up-button>
</view>
<view class="login-panel__foot">
<text class="login-panel__foot-text">还没有账号?</text>
<text class="login-panel__link" @click="switchMode(true)">立即注册</text>
</view>
</up-form>
</view>
</view>
</template>
<script setup lang="ts">
/**
* 登录 / 注册面板
*
* 与 new3(Web 端)`src/views/login/index.vue` 的账号密码登录 + 注册部分对齐。
* 已裁剪:微信扫码登录(小程序端不适用,小程序自身的微信登录属于另一条链路)。
*
* 设计约定:
* - 组件只负责「表单 + 校验 + 调接口」,登录成功只抛 success 事件;
* 跳转策略(回跳来源页 / 进工作台)由使用方决定,方便在弹窗等场景复用。
* - 失败提示由 `utils/request` 统一 toast,组件内不再重复提示。
*/
import { reactive, ref } from 'vue'
import { useUserStore } from '@/store/modules/user'
/** u-form 实例上本项目实际用到的方法 */
interface FormInstance {
validate: () => Promise<unknown>
clearValidate: (props?: string | string[]) => void
}
const props = withDefaults(
defineProps<{
/** 品牌 Logo,传空串则退化为内置图标 */
logo?: string
title?: string
desc?: string
/** 初始模式 */
initialMode?: 'login' | 'register'
}>(),
{
logo: '',
title: 'WMS 小程序',
desc: '仓储管理系统 · 微信小程序端',
initialMode: 'login'
}
)
const emit = defineEmits<{
(e: 'success'): void
(e: 'change', mode: 'login' | 'register'): void
}>()
const userStore = useUserStore()
const loginFormRef = ref<FormInstance | null>(null)
const registerFormRef = ref<FormInstance | null>(null)
const isRegister = ref(props.initialMode === 'register')
const loading = ref(false)
// ──────────────────────── 登录表单 ────────────────────────
const loginForm = reactive({
username: '',
password: ''
})
const loginRules = {
username: [{ required: true, message: '请输入账号', trigger: ['blur', 'change'] }],
password: [{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }]
}
// ──────────────────────── 注册表单 ────────────────────────
const registerForm = reactive({
username: '',
email: '',
real_name: '',
password: '',
confirmPassword: ''
})
/** 二次密码一致性校验(async-validator 标准签名,与 new3 的 el-form 写法一致) */
const validateConfirmPassword = (
_rule: unknown,
value: string,
callback: (error?: Error) => void
) => {
if (value !== registerForm.password) {
callback(new Error('两次输入的密码不一致'))
} else {
callback()
}
}
const registerRules = {
username: [{ required: true, message: '请输入账号', trigger: ['blur', 'change'] }],
password: [
{ required: true, message: '请输入密码', trigger: ['blur', 'change'] },
{ min: 6, message: '密码长度不能少于 6 位', trigger: ['blur', 'change'] }
],
confirmPassword: [
{ required: true, message: '请再次输入密码', trigger: ['blur', 'change'] },
{ validator: validateConfirmPassword, trigger: ['blur', 'change'] }
],
email: [{ type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }]
}
// ──────────────────────── 交互 ────────────────────────
/** 登录 / 注册模式切换 */
const switchMode = (register: boolean) => {
if (isRegister.value === register) return
isRegister.value = register
emit('change', register ? 'register' : 'login')
}
/** 登录:校验通过 → store.login → 通知使用方跳转 */
const handleLogin = () => {
if (loading.value) return
loginFormRef.value
?.validate()
.then(async () => {
loading.value = true
try {
await userStore.login({
username: loginForm.username,
password: loginForm.password
})
emit('success')
} catch {
// 失败提示已由 request 层统一 toast
} finally {
loading.value = false
}
})
.catch(() => {
// 表单校验失败:错误文案已展示在对应表单项上
})
}
/** 注册:校验通过 → store.register → 回到登录页并回填账号(与 new3 一致,不自动登录) */
const handleRegister = () => {
if (loading.value) return
registerFormRef.value
?.validate()
.then(async () => {
loading.value = true
try {
await userStore.register({
username: registerForm.username,
email: registerForm.email,
real_name: registerForm.real_name,
password: registerForm.password
})
uni.$u.toast('注册成功,请登录')
loginForm.username = registerForm.username.trim()
switchMode(false)
} catch {
// 失败提示已由 request 层统一 toast
} finally {
loading.value = false
}
})
.catch(() => {
// 表单校验失败:错误文案已展示在对应表单项上
})
}
</script>
<style lang="scss" scoped>
.login-panel {
padding: 0 48rpx;
&__brand {
display: flex;
flex-direction: column;
align-items: center;
padding: 72rpx 0 48rpx;
}
&__logo {
width: 140rpx;
height: 140rpx;
border-radius: 32rpx;
background-color: rgba(255, 255, 255, 0.18);
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
&__logo-img {
width: 140rpx;
height: 140rpx;
}
&__brand-title {
margin-top: 24rpx;
font-size: 44rpx;
font-weight: 600;
color: #ffffff;
letter-spacing: 2rpx;
}
&__brand-desc {
margin-top: 12rpx;
font-size: 26rpx;
color: rgba(255, 255, 255, 0.75);
}
&__card {
background-color: #ffffff;
border-radius: 24rpx;
padding: 40rpx 32rpx 32rpx;
box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.08);
}
&__head {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 24rpx;
}
&__head-title {
font-size: 36rpx;
font-weight: 600;
color: #303133;
}
&__head-sub {
margin-top: 10rpx;
font-size: 24rpx;
color: #909399;
}
&__submit {
margin-top: 48rpx;
}
&__foot {
display: flex;
align-items: center;
justify-content: center;
margin-top: 28rpx;
}
&__foot-text {
font-size: 26rpx;
color: #909399;
}
&__link {
margin-left: 8rpx;
font-size: 26rpx;
color: #2979ff;
}
}
</style>

1
src/composables/.gitkeep Normal file
View File

@ -0,0 +1 @@
组合式函数:useXxx 形式的可复用逻辑

10
src/env.d.ts vendored
View File

@ -1,5 +1,15 @@
/// <reference types="vite/client" />
/** .env.[mode] 注入的环境变量(仅 VITE_ 前缀会被暴露给客户端) */
interface ImportMetaEnv {
/** 接口根地址,见 .env.development / .env.production */
readonly VITE_APP_BASE_API: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
declare module '*.vue' {
import { DefineComponent } from 'vue'
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types

View File

@ -1,12 +1,17 @@
import { createSSRApp } from "vue";
import * as Pinia from "pinia";
import App from "./App.vue";
import uviewPlus from "uview-plus";
export function createApp() {
const app = createSSRApp(App);
// 状态管理:登录态等跨页面共享数据
// 注意:uni-app 小程序端必须把 Pinia 一并 return,否则各页面拿到的不是同一实例
app.use(Pinia.createPinia());
// 注册 uview-plus,注册后才可使用 uni.$u 等全局工具方法
app.use(uviewPlus);
return {
app,
Pinia,
};
}

View File

@ -1,7 +1,7 @@
{
"name" : "",
"name" : "WMS 小程序",
"appid" : "",
"description" : "",
"description" : "仓储管理系统 · 微信小程序端",
"versionName" : "1.0.0",
"versionCode" : "100",
"transformPx" : false,
@ -50,13 +50,28 @@
"quickapp" : {},
/* 小程序特有相关 */
"mp-weixin" : {
"appid" : "",
/* 微信小程序 AppID(公众平台 → 开发管理 → 开发设置) */
"appid" : "wx31f8d1ee127bc64b",
"projectname" : "wms_mp_weixin",
/* 微信开发者工具项目设置 */
"setting" : {
"urlCheck" : false
/* 是否校验安全域名与 TLS 版本:仅影响开发者工具内的请求校验,
不影响上传后的线上行为,本地联调常设为 false */
"urlCheck" : false,
"es6" : true,
"postcss" : true,
"minified" : true,
"bigPackageSizeSupport" : true
},
"usingComponents" : true,
/* uview-plus 要求:将虚拟节点属性合并到根节点,否则组件样式可能异常 */
"mergeVirtualHostAttributes" : true
"mergeVirtualHostAttributes" : true,
/* 按需注入:只注入当前页面需要的组件与代码,降低启动耗时(微信官方推荐) */
"lazyCodeLoading" : "requiredComponents",
/* 分包优化:分包内静态资源、仅被单个分包引用的 js 不计入主包体积 */
"optimization" : {
"subPackages" : true
}
},
"mp-alipay" : {
"usingComponents" : true

View File

@ -1,26 +1,96 @@
{
// easycom:uview-plus 组件按需自动引入,页面中无需手动 import
// 注意:修改 easycom 规则不会热更新,需重启编译才生效
"easycom": {
"autoscan": true,
// 规则必须写在 custom 中,否则无效
"custom": {
"^u--(.*)": "uview-plus/components/u-$1/u-$1.vue",
"^up-(.*)": "uview-plus/components/u-$1/u-$1.vue",
"^u-([^-].*)": "uview-plus/components/u-$1/u-$1.vue"
}
},
"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
"pages": [
{
"path": "pages/login/login",
"style": {
"navigationBarTitleText": "登录"
}
},
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "uni-app"
"navigationBarTitleText": "工作台"
}
},
{
"path": "pages/task/task",
"style": {
"navigationBarTitleText": "任务"
}
},
{
"path": "pages/inventory/inventory",
"style": {
"navigationBarTitleText": "库存"
}
},
{
"path": "pages/mine/mine",
"style": {
"navigationBarTitleText": "我的"
}
}
],
"tabBar": {
"color": "#909399",
"selectedColor": "#2979FF",
"backgroundColor": "#FFFFFF",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/index/index",
"text": "工作台"
},
{
"pagePath": "pages/task/task",
"text": "任务"
},
{
"pagePath": "pages/inventory/inventory",
"text": "库存"
},
{
"pagePath": "pages/mine/mine",
"text": "我的"
}
]
},
"condition": {
"current": 0,
"list": [
{
"name": "登录",
"path": "pages/login/login"
},
{
"name": "工作台",
"path": "pages/index/index"
},
{
"name": "任务",
"path": "pages/task/task"
},
{
"name": "库存",
"path": "pages/inventory/inventory"
},
{
"name": "我的",
"path": "pages/mine/mine"
}
]
},
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarTitleText": "WMS 小程序",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
}

View File

@ -1,23 +1,33 @@
<template>
<view class="content">
<image class="logo" src="/static/logo.png" />
<view class="text-area">
<text class="title">{{ title }}</text>
<view class="page">
<!-- 顶部欢迎区 -->
<view class="hero">
<view class="hero__title">工作台</view>
<view class="hero__desc">WMS 仓储管理 · 微信小程序端</view>
</view>
<!-- uview-plus 组件:已配置 easycom,无需 import 即可直接使用 -->
<view class="demo">
<up-button type="primary" text="主要按钮" @click="onClick"></up-button>
<up-button
type="success"
text="镂空按钮"
:plain="true"
customStyle="margin-top: 20rpx"
></up-button>
<!-- 常用功能入口 -->
<view class="card">
<view class="card__title">常用功能</view>
<view class="grid">
<view
v-for="item in entries"
:key="item.key"
class="grid__item"
@click="onEntry(item)"
>
<up-icon :name="item.icon" :color="item.color" size="26"></up-icon>
<text class="grid__item-text">{{ item.text }}</text>
</view>
</view>
</view>
<up-cell-group :border="false" customStyle="margin-top: 30rpx; width: 100%">
<up-cell title="uview-plus 版本" :value="version"></up-cell>
<up-cell title="运行平台" :value="platform"></up-cell>
<!-- 运行信息:用于确认各端编译正常 -->
<view class="card">
<view class="card__title">运行信息</view>
<up-cell-group :border="false">
<up-cell title="uview-plus 版本" :value="version" :border="false"></up-cell>
<up-cell title="运行平台" :value="platform" :border="false"></up-cell>
</up-cell-group>
</view>
</view>
@ -25,50 +35,93 @@
<script setup lang="ts">
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
const title = ref('Hello uview-plus')
interface EntryItem {
key: string
text: string
icon: string
color: string
}
// uni.$u 为 uview-plus 挂载的全局工具对象
const version = ref(uni.$u.config.v)
// 运行平台,用于确认各端编译结果
const platform = ref(uni.getSystemInfoSync().uniPlatform)
const onClick = () => {
uni.$u.toast('uview-plus 已成功引入')
// 业务入口。对应页面将放入分包(pagesA/B/C),待第 3 节注册分包后接入跳转
const entries = ref<EntryItem[]>([
{ key: 'inbound', text: '入库', icon: 'bag', color: '#2979ff' },
{ key: 'outbound', text: '出库', icon: 'car', color: '#19be6b' },
{ key: 'stocktaking', text: '盘点', icon: 'list', color: '#ff9900' },
{ key: 'scan', text: '扫码', icon: 'scan', color: '#303133' },
{ key: 'inventory', text: '库存查询', icon: 'search', color: '#909399' },
{ key: 'transfer', text: '调拨', icon: 'server-man', color: '#8a56e2' }
])
const onEntry = (item: EntryItem) => {
uni.$u.toast(`${item.text}:功能开发中`)
}
// onShow:tabBar 页切换只触发 onShow、不触发 onLoad
onShow(() => {
// TODO 第 5 节接入请求后,在此刷新待办数量等看板数据
})
</script>
<style lang="scss" scoped>
.content {
.page {
min-height: 100vh;
background-color: #f5f6fa;
padding-bottom: 24rpx;
}
.hero {
padding: 48rpx 32rpx 56rpx;
background-color: #2979ff;
&__title {
font-size: 44rpx;
font-weight: 600;
color: #ffffff;
}
&__desc {
margin-top: 12rpx;
font-size: 26rpx;
color: rgba(255, 255, 255, 0.8);
}
}
.card {
margin: 24rpx;
background-color: #ffffff;
border-radius: 16rpx;
overflow: hidden;
&__title {
padding: 24rpx 32rpx 8rpx;
font-size: 30rpx;
font-weight: 600;
color: #303133;
}
}
.grid {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
flex-wrap: wrap;
padding: 8rpx 0 24rpx;
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
&__item {
width: 33.333%;
display: flex;
flex-direction: column;
align-items: center;
padding: 24rpx 0;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: $uni-text-color-grey;
}
.demo {
width: 100%;
padding: 40rpx;
box-sizing: border-box;
&__item-text {
margin-top: 12rpx;
font-size: 26rpx;
color: #606266;
}
}
</style>

View File

@ -0,0 +1,92 @@
<template>
<view class="page">
<!-- 搜索区 -->
<view class="search">
<up-search
v-model="keyword"
placeholder="搜索商品 / 条码 / 库位"
@search="onSearch"
></up-search>
</view>
<!-- 扫码入口:仓储场景最高频操作 -->
<view class="actions">
<up-button
type="primary"
size="small"
icon="scan"
text="扫码查询"
@click="onScan"
></up-button>
</view>
<!-- 结果区:接口接入前保持空态 -->
<view class="body">
<up-empty v-if="list.length === 0" mode="data" :text="emptyText"></up-empty>
</view>
</view>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
const keyword = ref('')
// 库存列表数据,第 5 节接入接口后替换
const list = ref<unknown[]>([])
const emptyText = computed(() =>
keyword.value ? `没有找到「${keyword.value}」的库存记录` : '请输入条件查询库存'
)
const onSearch = () => {
// TODO 第 5 节接入请求后调用库存查询接口
uni.$u.toast('查询功能待接入接口')
}
/**
* 扫码查询
* 注意:uni.scanCode 属隐私接口,真机需先在微信公众平台配置
* 《小程序用户隐私保护指引》并声明「摄像头」,否则会被拦截(见清单第 7 节)
*/
const onScan = () => {
uni.scanCode({
scanType: ['barCode', 'qrCode'],
success: (res) => {
keyword.value = res.result
onSearch()
},
fail: () => {
uni.$u.toast('未完成扫码')
}
})
}
// onShow:tabBar 页切换只触发 onShow、不触发 onLoad
onShow(() => {
// TODO 第 5 节接入请求后,在此刷新库存列表
})
</script>
<style lang="scss" scoped>
.page {
min-height: 100vh;
background-color: #f5f6fa;
}
.search {
padding: 16rpx 24rpx 0;
background-color: #ffffff;
}
.actions {
display: flex;
padding: 20rpx 24rpx;
background-color: #ffffff;
}
.body {
padding-top: 24rpx;
}
</style>

98
src/pages/login/login.vue Normal file
View File

@ -0,0 +1,98 @@
<template>
<view class="login-page">
<scroll-view class="login-page__scroll" scroll-y>
<login-panel
:logo="logo"
title="WMS 小程序"
desc="仓储管理系统 · 微信小程序端"
@success="onLoginSuccess"
></login-panel>
<view class="login-page__tip">登录后可使用入库、出库、盘点等全部功能</view>
</scroll-view>
</view>
</template>
<script setup lang="ts">
/**
* 登录页
*
* 本页同时是**小程序的启动页**(pages.json 的 pages 数组第一项):
* - 未登录:停留在登录/注册
* - 已登录(上次登录留下的 token 仍有效):直接进工作台,不闪登录表单
*
* 与 new3 的对应关系:new3 靠 permission.ts 把未登录用户重定向到 /login?redirect=xxx,
* 小程序端由 `utils/auth-guard.ts` 的全局跳转拦截承担同样职责。
*/
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import LoginPanel from '@/components/login-panel/login-panel.vue'
import { getToken } from '@/utils/auth'
import { LOGIN_PAGE } from '@/utils/auth-guard'
/** 首页(tabBar 页) */
const HOME_PAGE = '/pages/index/index'
/** tabBar 页面清单:这些页面只能用 switchTab 进入 */
const TAB_PAGES = [
HOME_PAGE,
'/pages/task/task',
'/pages/inventory/inventory',
'/pages/mine/mine'
]
const logo = ref('/static/logo.png')
/** 登录成功后要回跳的目标页,由 auth-guard 通过 redirect 参数带入 */
const redirect = ref('')
/** 登录成功后进入目标页 */
const goAfterLogin = () => {
const raw = redirect.value || HOME_PAGE
const path = raw.split('?')[0]
const target = path === LOGIN_PAGE ? HOME_PAGE : raw
if (TAB_PAGES.includes(target.split('?')[0])) {
// tabBar 页必须用 switchTab
uni.switchTab({ url: target.split('?')[0] })
} else {
// 用 redirectTo 替换当前页,避免「返回」再次回到登录页
uni.redirectTo({ url: target })
}
}
const onLoginSuccess = () => {
goAfterLogin()
}
onLoad((options) => {
if (options?.redirect) {
redirect.value = decodeURIComponent(options.redirect)
}
})
// 已有 token(本次启动前登录过)直接放行,避免重复登录
onShow(() => {
if (getToken()) goAfterLogin()
})
</script>
<style lang="scss" scoped>
.login-page {
min-height: 100vh;
/* 上半屏品牌蓝,下半屏浅灰,与白卡片形成层次 */
background: linear-gradient(180deg, #2979ff 0%, #1a5fd0 40%, #f5f6fa 40%, #f5f6fa 100%);
}
.login-page__scroll {
height: 100vh;
}
.login-page__tip {
padding: 40rpx 48rpx 60rpx;
text-align: center;
font-size: 24rpx;
color: #a8abb2;
}
</style>

153
src/pages/mine/mine.vue Normal file
View File

@ -0,0 +1,153 @@
<template>
<view class="page">
<!-- 用户信息:未登录时点击可进入登录页 -->
<view class="profile" @click="onProfileTap">
<view class="profile__avatar">
<up-icon name="account" color="#ffffff" size="34"></up-icon>
</view>
<view class="profile__info">
<view class="profile__name">{{ userName }}</view>
<view class="profile__desc">{{ userDesc }}</view>
</view>
<up-icon v-if="!userStore.isLogin" name="arrow-right" color="#ffffff" size="16"></up-icon>
</view>
<!-- 运行信息与常用项 -->
<view class="card">
<up-cell-group :border="false">
<up-cell title="当前版本" :value="version" :border="false"></up-cell>
<up-cell title="运行平台" :value="platform" :border="false"></up-cell>
<up-cell title="清除本地缓存" is-link @click="onClearCache"></up-cell>
</up-cell-group>
</view>
<view class="footer">
<up-button type="info" :plain="true" text="退出登录" @click="onLogout"></up-button>
</view>
</view>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/modules/user'
import { getToken } from '@/utils/auth'
import { LOGIN_PAGE } from '@/utils/auth-guard'
const version = ref(uni.$u.config.v)
const platform = ref(uni.getSystemInfoSync().uniPlatform)
const userStore = useUserStore()
const userName = computed(() => {
if (!userStore.isLogin) return '未登录'
return userStore.userName || '已登录'
})
const userDesc = computed(() => {
if (!userStore.isLogin) return '点击登录后使用完整功能'
return userStore.employeeId ? `员工 ID:${userStore.employeeId}` : '已登录'
})
/** 未登录时点击头部跳登录页(已登录则不做任何事) */
const onProfileTap = () => {
if (userStore.isLogin) return
uni.navigateTo({ url: LOGIN_PAGE })
}
const onClearCache = () => {
uni.showModal({
title: '提示',
content: '确定要清除本地缓存吗?登录状态会一并清除。',
success: (res) => {
if (!res.confirm) return
uni.clearStorageSync()
uni.$u.toast('缓存已清除')
// 存储被清空后同步内存登录态,避免界面仍显示已登录
userStore.resetToken()
}
})
}
const onLogout = () => {
if (!userStore.isLogin) {
uni.$u.toast('当前未登录')
return
}
uni.showModal({
title: '提示',
content: '确定要退出登录吗?',
success: async (res) => {
if (!res.confirm) return
// logout 内部已做兜底:后端不可用也会清理本地登录态
await userStore.logout()
uni.reLaunch({ url: LOGIN_PAGE })
}
})
}
// onShow:tabBar 页切换只触发 onShow,登录态变化后需在此刷新
onShow(() => {
// 本地存储是登录态的唯一来源,先与内存态对齐
// (request 层在 401/过期时会直接清存储,此处保证界面同步)
userStore.token = getToken()
if (!userStore.isLogin) return
if (userStore.userName) return
// 首次进入且尚未拉取过用户信息时补齐(失败提示由 request 层统一处理)
userStore.getInfo().catch(() => {})
})
</script>
<style lang="scss" scoped>
.page {
min-height: 100vh;
background-color: #f5f6fa;
}
.profile {
display: flex;
align-items: center;
padding: 48rpx 32rpx;
background-color: #2979ff;
&__avatar {
width: 108rpx;
height: 108rpx;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.25);
display: flex;
align-items: center;
justify-content: center;
}
&__info {
flex: 1;
margin-left: 24rpx;
}
&__name {
font-size: 36rpx;
font-weight: 600;
color: #ffffff;
}
&__desc {
margin-top: 8rpx;
font-size: 26rpx;
color: rgba(255, 255, 255, 0.8);
}
}
.card {
margin: 24rpx;
background-color: #ffffff;
border-radius: 16rpx;
overflow: hidden;
}
.footer {
padding: 24rpx 32rpx;
}
</style>

111
src/pages/task/task.vue Normal file
View File

@ -0,0 +1,111 @@
<template>
<view class="page">
<!-- 搜索区 -->
<view class="search">
<up-search
v-model="keyword"
placeholder="搜索单号 / 商品名称"
@search="onSearch"
></up-search>
</view>
<!-- 状态分段:用原生 view 实现,避免额外组件依赖 -->
<view class="segment">
<view
v-for="(item, index) in segments"
:key="item"
class="segment__item"
:class="{ 'segment__item--active': index === activeIndex }"
@click="onSegmentChange(index)"
>
{{ item }}
</view>
</view>
<!-- 列表区:接口接入前保持空态 -->
<view class="body">
<up-empty v-if="list.length === 0" mode="list" :text="emptyText"></up-empty>
</view>
</view>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
const segments = ['待处理', '已处理', '全部']
const activeIndex = ref(0)
const keyword = ref('')
// 任务列表数据,第 5 节接入接口后替换
const list = ref<unknown[]>([])
const emptyText = computed(() =>
keyword.value ? `没有找到「${keyword.value}」相关任务` : '暂无任务'
)
const onSearch = () => {
// TODO 第 5 节接入请求后调用任务列表接口
uni.$u.toast('搜索功能待接入接口')
}
const onSegmentChange = (index: number) => {
activeIndex.value = index
}
// onLoad:读取路由参数,做一次性初始化
onLoad((options) => {
const status = options?.status
if (!status) return
const index = segments.indexOf(status)
if (index > -1) activeIndex.value = index
})
// onShow:tabBar 页切换只触发 onShow、不触发 onLoad,列表刷新应放在这里
onShow(() => {
// TODO 第 5 节接入请求后,在此刷新当前分段的列表
})
</script>
<style lang="scss" scoped>
.page {
min-height: 100vh;
background-color: #f5f6fa;
}
.search {
padding: 16rpx 24rpx 0;
background-color: #ffffff;
}
.segment {
display: flex;
background-color: #ffffff;
padding: 16rpx 24rpx 20rpx;
&__item {
flex: 1;
height: 64rpx;
line-height: 64rpx;
text-align: center;
font-size: 28rpx;
color: #606266;
background-color: #f5f6fa;
border-radius: 8rpx;
margin-right: 16rpx;
&:last-child {
margin-right: 0;
}
&--active {
color: #ffffff;
background-color: #2979ff;
}
}
}
.body {
padding-top: 24rpx;
}
</style>

2
src/pagesA/.gitkeep Normal file
View File

@ -0,0 +1,2 @@
分包 A(规划:入库业务)
需在 pages.json 的 subPackages 中注册后生效,见开发清单第 3 节

2
src/pagesB/.gitkeep Normal file
View File

@ -0,0 +1,2 @@
分包 B(规划:出库业务)
需在 pages.json 的 subPackages 中注册后生效,见开发清单第 3 节

2
src/pagesC/.gitkeep Normal file
View File

@ -0,0 +1,2 @@
分包 C(规划:库存 / 盘点)
需在 pages.json 的 subPackages 中注册后生效,见开发清单第 3 节

1
src/store/.gitkeep Normal file
View File

@ -0,0 +1 @@
状态管理:Pinia store 定义,见开发清单第 8 节

132
src/store/modules/user.ts Normal file
View File

@ -0,0 +1,132 @@
/**
* 用户 / 登录态 Store
*
* 对应 new3(Web 端)的 `src/stores/modules/user.ts`。
* 已裁剪的部分(属后续「页面渲染框架」步骤,本次不做):
* - changeRole(切换角色/仓库,需配合页签与用户偏好重置)
* - 打印组件连接、用户偏好加载
*
* token 的**唯一真实来源是 utils/auth 的本地存储**,本 store 的 token 仅为 UI 响应式副本。
*/
import { defineStore } from 'pinia'
import { getToken, removeToken, setToken } from '@/utils/auth'
import {
login as apiLogin,
register as apiRegister,
getInfo as apiGetInfo,
logout as apiLogout
} from '@/api/user/user'
/** 登录请求携带的端标记:与 Web 端(desktop / mobile)区分,小程序端固定 mobile */
const DEVICE = 'mobile'
interface UserInfo {
[key: string]: any
}
interface UserState {
token: string
user: UserInfo
roleId: number
permissions: string[]
}
export const useUserStore = defineStore('user', {
state: (): UserState => ({
token: getToken(),
user: {},
roleId: 0,
permissions: []
}),
getters: {
/** 是否已登录 */
isLogin: (state): boolean => !!state.token,
/** 展示用名称:优先员工姓名,兼容 username / name */
userName: (state): string =>
state.user.employees_name || state.user.username || state.user.name || '',
/** 员工 ID */
employeeId: (state): number => state.user.employees_id || state.roleId || 0
},
actions: {
/** 账号密码登录:成功后写入 token(与 new3 相同,登录不立即拉用户信息) */
async login(payload: { username: string; password: string }): Promise<true> {
const resp = await apiLogin({
username: payload.username.trim(),
password: payload.password,
device: DEVICE
})
const token = resp.data?.token || ''
if (!token) {
throw new Error('登录失败:未获取到 token')
}
setToken(token)
this.token = token
return true
},
/** 注册账号 */
async register(payload: {
username: string
email: string
real_name: string
password: string
}): Promise<void> {
await apiRegister({
username: payload.username.trim(),
email: payload.email.trim(),
real_name: payload.real_name.trim(),
password: payload.password
})
},
/** 拉取用户信息(权限点 + 菜单),后续页面渲染框架会消费 menus */
async getInfo(): Promise<UserInfo> {
const resp = await apiGetInfo({ device: DEVICE })
const user = resp.data
if (!user) {
throw new Error('获取用户信息失败,请重新登录')
}
this.user = user
this.permissions = user.permissions || []
this.roleId = user.employees_id || 0
return user
},
/** 退出登录:先通知后端,无论成功与否都要清掉本地登录态 */
async logout(): Promise<void> {
try {
await apiLogout({})
} catch {
// 后端不可用不应阻塞退出
} finally {
this.resetToken()
}
},
/** 清空本地登录态 */
resetToken(): void {
removeToken()
this.token = ''
this.user = {}
this.roleId = 0
this.permissions = []
},
/** 更新 token(响应头续期的场景由 request 层写入存储,这里同步内存副本) */
updateToken(token: string): void {
setToken(token)
this.token = token
},
/** 权限点判断 */
checkPermission(key: string): boolean {
return this.permissions.includes(key)
}
}
})

1
src/utils/.gitkeep Normal file
View File

@ -0,0 +1 @@
纯工具函数:auth(登录态)/ scan(扫码)/ format(格式化)等

75
src/utils/auth-guard.ts Normal file
View File

@ -0,0 +1,75 @@
/**
* 登录守卫
*
* 对应 new3(Web 端)的 `src/permission.ts`:
* Web 端靠 vue-router 的 beforeEach 拦截未登录访问,
* 小程序没有路由守卫,改用 `uni.addInterceptor` 拦截所有跳转 API,效果等价。
*
* 覆盖范围:navigateTo / redirectTo / reLaunch / switchTab 四个跳转 API,
* 基本等同于「页面级」访问控制。
*/
import { getToken } from './auth'
/** 登录页路径(路由拦截与 401 跳转的唯一来源,改路径只需改这里) */
export const LOGIN_PAGE = '/pages/login/login'
/** 免登录白名单 */
const WHITE_LIST: string[] = [LOGIN_PAGE]
/** 跳转登录页的节流标记,避免并发 401 触发多次 reLaunch */
let redirecting = false
/** 取当前页面完整路径(用于登录成功后回跳) */
export function getCurrentRoute(): string {
const pages = getCurrentPages() as unknown as Array<{ route?: string }>
const current = pages[pages.length - 1]
return current?.route ? `/${current.route}` : ''
}
/**
* 导向登录页
* @param redirect 登录成功后要回跳的页面路径,缺省取当前页
*/
export function redirectToLogin(redirect?: string): void {
if (redirecting) return
const target = redirect ?? getCurrentRoute()
const path = target.split('?')[0]
const query =
path && path !== LOGIN_PAGE ? `?redirect=${encodeURIComponent(target)}` : ''
redirecting = true
uni.reLaunch({
url: `${LOGIN_PAGE}${query}`,
complete: () => {
// 留出缓冲:reLaunch 完成前若再触发拦截,也不重复跳转
setTimeout(() => {
redirecting = false
}, 800)
}
})
}
/**
* 注册全局路由拦截:未登录时阻止跳转并导向登录页
* 需在应用启动时调用一次(见 App.vue 的 onLaunch)
*/
export function setupAuthGuard(): void {
const apis = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab'] as const
apis.forEach((api) => {
uni.addInterceptor(api, {
invoke(args: { url?: string }) {
const path = (args?.url || '').split('?')[0]
// 白名单与无路径的调用(如 navigateBack 的占位)直接放行
if (!path || WHITE_LIST.includes(path)) return args
if (getToken()) return args
// 返回 false 取消本次跳转,同时导向登录页
redirectToLogin(args.url)
return false
}
})
})
}

40
src/utils/auth.ts Normal file
View File

@ -0,0 +1,40 @@
/**
* 登录令牌的本地存取
*
* 与 new3(Web 端)的差异:Web 用 js-cookie 存 Cookie,小程序没有 Cookie,
* 因此统一改用 uni 的本地存储;存储 key 保持与 new3 一致(token)。
*
* 约定:本文件是 token 的**唯一写入方**,其他模块只允许通过这里读写,
* 避免出现「有的地方读 Cookie、有的地方读 Storage」的不一致。
*/
const TOKEN_KEY = 'token'
/** 读取 token;未登录返回空字符串(调用方用真值判断即可) */
export function getToken(): string {
try {
const token = uni.getStorageSync(TOKEN_KEY)
return typeof token === 'string' ? token : ''
} catch {
return ''
}
}
/** 写入 token */
export function setToken(token: string): void {
if (!token) return
try {
uni.setStorageSync(TOKEN_KEY, token)
} catch {
// 存储写入失败(如空间不足)时静默忽略:内存态仍有效,下次请求会重新读取
}
}
/** 清除 token */
export function removeToken(): void {
try {
uni.removeStorageSync(TOKEN_KEY)
} catch {
// ignore
}
}

258
src/utils/request.ts Normal file
View File

@ -0,0 +1,258 @@
/**
* 请求封装(基于 uni.request)
*
* 对应 new3(Web 端)的 `src/utils/request.ts`,行为保持对齐:
* 1. baseURL 取 .env 的 VITE_APP_BASE_API
* 2. 请求头注入 platform / project / Authorization: Bearer <token>
* 3. 响应头若带回新 token(续期场景),自动回写本地存储
* 4. 统一业务码判定:非成功码 → 提示并 reject
* 5. 401 / 50008 / 50012 / 50014 → 清除登录态并回登录页
*
* 与 new3 的差异(小程序端限制所致):
* - axios → uni.request
* - new3 的 `isSystemApi` 标记在那边**从未被消费**(死字段),故不移植
* - 不反向依赖 Pinia store,避免 request ↔ store ↔ api 的循环引用;
* token 以 utils/auth 的本地存储为唯一来源
*/
import { getToken, removeToken, setToken } from './auth'
import { redirectToLogin } from './auth-guard'
/** 接口根地址,来自 .env.[mode] */
const BASE_URL = (import.meta.env.VITE_APP_BASE_API as string) || ''
/** 请求头 platform 标记:小程序端与 Web 端('web')区分,便于后端统计来源 */
let platform = 'web'
// #ifdef MP-WEIXIN
platform = 'mp-weixin'
// #endif
/** 业务成功码:后端 /system 网关以 code=1 表示成功,其余为兼容保留 */
const SUCCESS_CODES = [1, 0, 200, 20000]
/** 登录失效业务码:命中后清 token 并回登录页 */
const TOKEN_EXPIRED_CODES = [401, 50008, 50012, 50014]
/** 无权限业务码 */
const NO_PERMISSION_CODES = [403, 40005, 40006]
/** 业务错误码 → 兜底文案(后端返回 message 时优先用后端的) */
const ERROR_CODE_MAP: Record<string, string> = {
400: '请求参数错误',
401: '未授权访问',
403: '禁止访问',
404: '资源不存在',
409: '资源冲突',
422: '参数验证失败',
500: '服务器内部错误',
40001: '用户名或密码错误',
40002: '账号已被禁用',
40003: '验证码错误',
40004: '账号不存在',
40005: '没有操作权限',
40006: '访问被拒绝',
40010: '数据不存在',
40011: '数据重复',
40012: '参数验证失败',
50008: '非法的 token',
50012: '其他客户端登录',
50014: 'Token 过期'
}
/** HTTP 状态码 → 文案 */
const HTTP_STATUS_MAP: Record<number, string> = {
400: '请求参数错误',
401: '未授权,请重新登录',
403: '拒绝访问,没有操作权限',
404: '请求资源不存在',
405: '请求方法不被允许',
406: '仓库有效期过期,拒绝访问',
408: '请求超时',
500: '服务器内部错误',
501: '服务未实现',
502: '网关错误',
503: '服务不可用',
504: '网关超时',
505: 'HTTP 版本不受支持'
}
/** 后端统一响应结构 */
export interface BizResponse<T = any> {
code: number
message?: string
msg?: string
data: T
}
export interface RequestOptions {
url: string
method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
/** 请求体(POST / PUT 生效) */
data?: Record<string, any>
/** URL 查询参数,会拼接到 url 之后 */
params?: Record<string, any>
header?: Record<string, string>
timeout?: number
/** 传入文案则自动 showLoading / hideLoading */
loading?: string
/** 失败时是否自动 toast,默认 true */
toastError?: boolean
}
/** 统一提示:优先用 uview-plus 的 toast,保证与页面内提示风格一致 */
function toast(message: string): void {
const $u = (uni as unknown as { $u?: { toast?: (text: string) => void } }).$u
if ($u && typeof $u.toast === 'function') {
$u.toast(message)
} else {
uni.showToast({ title: message, icon: 'none' })
}
}
/** 拼装完整请求地址 */
function buildUrl(url: string, params?: Record<string, any>): string {
const full = /^https?:\/\//i.test(url)
? url
: `${BASE_URL.replace(/\/+$/, '')}/${url.replace(/^\/+/, '')}`
if (!params) return full
const query = Object.keys(params)
.filter((key) => params[key] !== undefined && params[key] !== null)
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(String(params[key]))}`)
.join('&')
if (!query) return full
return full.includes('?') ? `${full}&${query}` : `${full}?${query}`
}
/** 响应头键名大小写归一,便于不区分大小写地取值 */
function normalizeHeader(header: Record<string, string> | undefined): Record<string, string> {
const result: Record<string, string> = {}
if (!header) return result
Object.keys(header).forEach((key) => {
result[key.toLowerCase()] = header[key]
})
return result
}
/** 响应头带回新 token 时回写本地存储(new3 同样有此逻辑,用于 token 续期) */
function syncRenewedToken(header: Record<string, string>): void {
const raw = header['authorization'] || header['new-authorization']
if (!raw) return
const value = /^bearer\s+/i.test(raw) ? raw.replace(/^bearer\s+/i, '').trim() : raw.trim()
if (value && value !== getToken()) {
setToken(value)
}
}
/**
* 发起请求
* @returns 后端响应体(未解包 data,与 new3 的拦截器行为一致)
*/
export default function request<T = any>(options: RequestOptions): Promise<BizResponse<T>> {
const {
url,
method = 'POST',
data,
params,
header,
timeout = 15000,
loading,
toastError = true
} = options
const token = getToken()
if (loading) {
uni.showLoading({ title: loading, mask: true })
}
return new Promise<BizResponse<T>>((resolve, reject) => {
uni.request({
url: buildUrl(url, params),
method,
data,
timeout,
header: {
'content-type': 'application/json',
platform,
project: 'all',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...header
},
success: (res) => {
syncRenewedToken(normalizeHeader(res.header as Record<string, string>))
const status = res.statusCode
const body = res.data as BizResponse<T>
// ── HTTP 层:非 2xx ──
if (status < 200 || status >= 300) {
if (status === 401) {
redirectToLogin()
reject(new Error('未授权,请重新登录'))
return
}
const message = HTTP_STATUS_MAP[status] || `连接错误 ${status}`
if (toastError) toast(message)
reject(new Error(message))
return
}
// ── 响应体异常(如网关返回 HTML)──
if (!body || typeof body !== 'object' || body.code === undefined) {
const message = '响应数据格式异常'
if (toastError) toast(message)
reject(new Error(message))
return
}
// ── 业务层:非成功码 ──
if (!SUCCESS_CODES.includes(body.code)) {
const message =
body.message || body.msg || ERROR_CODE_MAP[body.code] || '请求失败'
if (TOKEN_EXPIRED_CODES.includes(body.code)) {
redirectToLogin()
reject(new Error(message))
return
}
if (toastError) toast(NO_PERMISSION_CODES.includes(body.code) ? '没有操作权限' : message)
reject(new Error(message))
return
}
resolve(body)
},
fail: (err) => {
const raw = (err as { errMsg?: string })?.errMsg || ''
const message = /timeout/i.test(raw)
? '请求超时,请检查网络连接'
: '网络连接异常,请检查网络'
if (toastError) toast(message)
reject(new Error(message))
},
complete: () => {
if (loading) uni.hideLoading()
}
})
})
}
/** 常用方法快捷封装(与 new3 的 http 对象对齐) */
export const http = {
get<T = any>(url: string, params: Record<string, any> = {}, options: Partial<RequestOptions> = {}) {
return request<T>({ url, method: 'GET', params, ...options })
},
post<T = any>(url: string, data: Record<string, any> = {}, options: Partial<RequestOptions> = {}) {
return request<T>({ url, method: 'POST', data, ...options })
},
put<T = any>(url: string, data: Record<string, any> = {}, options: Partial<RequestOptions> = {}) {
return request<T>({ url, method: 'PUT', data, ...options })
},
delete<T = any>(url: string, params: Record<string, any> = {}, options: Partial<RequestOptions> = {}) {
return request<T>({ url, method: 'DELETE', params, ...options })
}
}

View File

@ -0,0 +1,499 @@
# WMS 微信小程序 · 开发清单
> 项目:`wms_mp_weixin`(仓储管理系统 · 微信小程序端)
> 技术栈:uni-app 3(Vue 3 + Vite)+ TypeScript + uview-plus 3.8
> 主目标平台:微信小程序(同时可选编译 H5)
> 生成日期:2026-09-18
---
## 0. 当前状态速览
| 项 | 状态 | 说明 |
|---|---|---|
| uni-app + Vue3 + TS 工程 | ✅ 已完成 | CLI/Vite 工程,TS 6 + vue-tsc 3 |
| uview-plus UI 框架 | ✅ 已完成 | easycom 按需引入,实测仅打包所用组件 |
| 类型检查 / 双端构建 | ✅ 通过 | `type-check`、`build:mp-weixin`、`build:h5` |
| 微信 AppID | ✅ 已配置 | `wx31f8d1ee127bc64b`,已实测写入产物 `project.config.json` |
| 应用名称 | ✅ 已配置 | `WMS 小程序` |
| 按需注入 / 分包优化 | ✅ 已开启 | 产物 `app.json` 已含 `lazyCodeLoading` |
| 目录结构(第 2 节) | ✅ 已完成 | 已建 `api` / `components` / `composables` / `store` / `utils` / 分包目录 |
| 页面框架(tabBar) | ✅ 已完成 | 4 个底部 Tab:工作台 / 任务 / 库存 / 我的(纯文字)|
| tabBar 图标 | ❌ 待补充 | 需本地图片 ≤ 40KB、81×81px |
| 分包(pages.json 注册) | ❌ 未注册 | 目录已建,待第 3 节注册到 `subPackages` |
| 请求封装(第 5 节) | ✅ 已完成 | `utils/request.ts`,对齐 new3,含 token 注入 / 响应头续期 / 401 处理 |
| 登录鉴权(第 6 节) | ✅ 已完成 | 账号密码登录 + 注册;`pages/login/login` 为启动页;`utils/auth-guard.ts` 全局跳转拦截 |
| Pinia 状态管理(第 8 节) | ✅ 已完成 | `pinia@2.1.7`(Vue 3.4 兼容版),见 `store/modules/user.ts` |
| 环境变量(第 11 节) | ✅ 已完成 | `.env.development` / `.env.production` 的 `VITE_APP_BASE_API` |
| 微信一键登录 / 扫码登录 | ❌ 未做 | 属另一条链路(`uni.login` → `user.loginByCode`),本次范围外 |
> 已知坑:同时跑两个 `dev:mp-weixin` 进程会写坏产物,导致预览报
> `ENOENT ... common/assets.js`。详见第 9 节。
---
## 1. 工程与构建配置
- [x] **填写微信 AppID** ✅
位置:`src/manifest.json` → `mp-weixin.appid`,已填 `wx31f8d1ee127bc64b`
> 实测确认已写入产物 `dist/build/mp-weixin/project.config.json` 的 `appid` 字段。
- [x] **补充应用基础信息** ✅
`name` = `WMS 小程序`、`description` = `仓储管理系统 · 微信小程序端`;
`versionName` / `versionCode` 保持 `1.0.0` / `100`。
> 注意:`manifest.json` 顶层的 `appid` 是 **DCloud 应用标识**,与微信 AppID 不是一个东西,保持为空即可。
- [x] **确认 `mp-weixin.projectname`** ✅
已设为 `wms_mp_weixin`,实测已同步到产物 `project.config.json`。
- [ ] **不要在 `src` 下创建 `project.wx.json`(实测结论,原「建议创建」已推翻)** ⚠️
文档提到 `src/project.wx.json`(或 `src/project.config.json`)可“自定义微信项目配置”,
但**实测结论是「整体替换」而非「合并」**:一旦创建该文件,
uni-app 生成的 `project.config.json` 会被它**完全覆盖**,
连 `appid`、`setting`、`compileType`、`condition` 都会一并丢失,
后果是微信开发者工具里项目没有 AppID,无法预览。
实测记录(uni-app 3.0.0-5020420260813003 CLI):
| 状态 | 产物 `project.config.json` |
|---|---|
| 无该文件 | `appid` / `setting` / `compileType` / `projectname` / `condition` 全部正常生成 ✅ |
| 有该文件 | **仅剩文件里写的字段**,其余全部丢失 ❌ |
**结论:本项目不启用该文件,以 `manifest.json` 的 `mp-weixin` 节点作为唯一配置来源。**
如确需配置 manifest 未覆盖的字段(如 `packOptions.ignore`、`libVersion`),
必须把完整配置(含 `appid`、`setting`、`compileType`)全部写进去,
并接受 appid 两处维护的漂移风险。
- [x] **开启小程序按需注入** ✅
`src/manifest.json` → `mp-weixin.lazyCodeLoading: "requiredComponents"`
> 实测确认产物 `app.json` 已包含 `"lazyCodeLoading": "requiredComponents"`。
- [x] **开启分包优化** ✅
`src/manifest.json` → `mp-weixin.optimization.subPackages: true`
注意:字段名是 `subPackages`(驼峰),写成 `subpackages` 无效。
作用:分包目录下的静态资源与仅被单个分包引用的 js 不再计入主包体积。
> 当前尚无分包,实际收益需等第 3 节划分分包后体现。
- [x] **确认 `setting` 各项** ✅
| 项 | 值 | 说明 |
|---|---|---|
| `urlCheck` | `false` | 仅控制**开发者工具内**是否校验安全域名。**不影响上传后的线上行为** —— 真机与线上始终由微信服务端校验域名白名单,所以提审不需要改它 |
| `es6` | `true` | ES6 转 ES5(使用手势组件会被强制开启) |
| `postcss` | `true` | 上传代码时样式自动补全 |
| `minified` | `true` | 上传代码时自动压缩(不影响本地调试编译) |
| `bigPackageSizeSupport` | `true` | 预览/真机调试时包体积上限提升到 4M |
> 实测确认这 5 项均已写入产物 `project.config.json` 的 `setting`。
- [x] **`transformPx` 保持 `false`** ✅
该选项已废弃,仅部分平台生效,新项目不推荐开启(当前已是 `false`,保持即可)。
- [ ] **(暂缓)配置 `sitemap.json`**
不配置时微信使用默认索引规则(收录全部页面)。
内部仓储工具通常不需要被微信搜索收录,故暂缓;若需禁止收录或精细控制,再补该文件。
- [x] **不要提交个人调试配置** ✅
微信开发者工具会在打开的产物目录生成 `project.private.config.json`;
因产物位于 `dist/`(已在 `.gitignore` 中),无需额外处理。
若改为直接在 `src` 下调试,则需追加忽略规则。
---
## 2. 目录结构规范
### 2.1 当前结构
```
d:\wechat\
├── index.html # H5 端入口模板
├── package.json # 依赖与多端编译脚本
├── tsconfig.json # TS 配置
├── vite.config.ts # Vite 配置(挂载 uni 插件)
├── 微信小程序开发清单.md # 本清单
└── src/
├── main.ts # 应用入口
├── App.vue # 根组件(全局样式 + 应用生命周期)
├── pages.json # 路由 / tabBar / easycom
├── manifest.json # 各端打包配置(微信端唯一来源)
├── uni.scss # 全局 SCSS 变量
├── env.d.ts # 类型声明
├── shims-uni.d.ts # 生命周期类型扩展(已修正拼写)
├── api/ # 接口层
│ └── user/user.ts # 登录 / 注册 / 用户信息 / 退出(/system 网关)
├── components/ # 全局组件(easycom 扫描)
│ └── login-panel/login-panel.vue # 登录 / 注册面板组件
├── composables/ # 组合式函数
├── store/ # 状态管理(Pinia)
│ └── modules/user.ts # 登录态(token / 用户信息 / 权限点)
├── utils/ # 工具函数
│ ├── auth.ts # token 本地存取(唯一写入方)
│ ├── auth-guard.ts # 全局跳转拦截(等价 new3 的 permission.ts)
│ └── request.ts # uni.request 封装
├── pages/ # 主包页面(启动页 + tabBar 页)
│ ├── login/login.vue # 登录 / 注册页(pages 第一项 = 启动页)
│ ├── index/index.vue # 工作台
│ ├── task/task.vue # 任务
│ ├── inventory/inventory.vue # 库存
│ └── mine/mine.vue # 我的
├── pagesA/ # 分包 A(规划:入库,待注册)
├── pagesB/ # 分包 B(规划:出库,待注册)
├── pagesC/ # 分包 C(规划:库存/盘点,待注册)
└── static/ # 静态资源
└── logo.png
```
> 空目录下均有 `.gitkeep` 占位(git 不跟踪空目录),内容行标注了该目录用途。
> 实测确认 `.gitkeep` **不会**被打进小程序产物。
### 2.2 目录职责说明
- [x] **按业务域补齐目录** ✅(已创建,见 2.1)
| 目录 | 职责 | 约定 |
|---|---|---|
| `api/` | 接口定义,按业务模块拆分 | `request.ts` 为请求实例;后续按入库/出库/库存拆文件(第 5 节) |
| `components/` | 全局自定义组件 | ⚠️ 必须符合 `组件名/组件名.vue` 才会被 easycom 自动扫描 |
| `composables/` | 组合式函数 | 命名 `useXxx` |
| `pages/` | 主包页面:tabBar 页 + 启动必需页 | 必须在 `pages.json` 的 `pages` 中注册 |
| `pagesA/` `pagesB/` `pagesC/` | 分包页面 | 路径相对 `root`;需在 `pages.json` 的 `subPackages` 中注册(第 3 节) |
| `static/` | 静态资源 | 唯一保证原样拷贝、不参与编译的目录 |
| `store/` | 状态管理(Pinia) | 需引入 Pinia 并注册(第 8 节) |
| `utils/` | 纯工具函数 | `auth` / `scan` / `format` 等(第 6 节) |
> 分包目录名 `pagesA/B/C` 与业务映射(入库/出库/库存)是**按 WMS 常见划分提的方案**。
> 若你们已有既定模块划分,现在改成本极低(尚无页面文件),只需重命名目录。
- [x] **遵守 uni-app 目录约定** ✅
- 页面必须同时在 `pages.json` 中注册,**新增/删除页面都要同步维护该数组**
- 页面路径不含后缀,uni-app 自动寻找 `.vue`
- `static/` 是唯一保证原样拷贝、不参与编译的目录,图片/字体放这里
- 每一层 `pages` 目录的第一项为该包的入口页(主包第一项即小程序首页)
- [x] **清理工程历史遗留** ✅
- 根目录 `shims-uni.d.ts` 不在 `tsconfig.json` 的 `include`(仅 `src/**`)范围内,**是死代码** → **已删除**
- `src/shime-uni.d.ts` 文件名拼写有误 → **已重命名为 `src/shims-uni.d.ts`**
> 两者功能重复,保留 `src/shims-uni.d.ts`(`declare module "vue"` 方式对 Vue 3 才是正确写法)。
> 重命名后已实测:`type-check` + 双端构建均通过。
---
## 3. 包体积与分包(微信硬性限制)
- [ ] **牢记体积红线**
| 限制项 | 上限 |
|---|---|
| 单个分包 / 主包 | **2 MB** |
| 所有分包 + 主包总计 | **20 MB** |
| 本地存储单个 key | 1 MB |
| 本地存储总量 | 10 MB |
- [ ] **规划分包**(`src/pages.json` → `subPackages`)
原则:主包只放 tabBar 页 + 启动必需页 + 公共资源;业务模块全部下沉到分包。
```jsonc
"subPackages": [
{ "root": "pagesA", "pages": [ { "path": "inbound/list", "style": { ... } } ] }
]
```
注意:分包内 `pages` 的路径是相对 `root` 的**相对路径**,不是全路径。
- [ ] **配置分包预下载**(`preloadRule`)
在进入某页面时提前下载后续可能用到的分包,减少二次跳转等待。
`packages` 取分包 `root` 或 `name`;`__APP__` 代表主包;`network` 可选 `all` / `wifi`。
- [ ] **图片资源策略**
体积大的图片、图标一律走 CDN 或对象存储,**不要打进代码包**。
包内仅保留 tabBar 图标、少量占位图。
- [ ] **构建产物体积巡检**
每次发版前用微信开发者工具的「代码依赖分析」查看主包/分包体积,确认无越线。
---
## 4. 页面与导航
- [x] **配置 tabBar** ✅(4 个纯文字 Tab)
| Tab | 页面路径 | 页面内容 |
|---|---|---|
| 工作台 | `pages/index/index` | 业务入口九宫格(入库/出库/盘点/扫码/库存查询/调拨)+ 运行信息 |
| 任务 | `pages/task/task` | 待处理/已处理/全部 分段 + 空态 |
| 库存 | `pages/inventory/inventory` | 搜索 + 扫码查询 + 空态 |
| 我的 | `pages/mine/mine` | 登录态展示(未登录可点击去登录)+ 运行信息 + 清除缓存 + 退出登录 |
约定(务必遵守):
- `list` 最少 2 个、最多 5 个;**tabBar 页必须在主包**,不能放分包
- 跳转到 tabBar 页只能用 `uni.switchTab`,**不能**用 `navigateTo` / `redirectTo`
- tabBar 页首次进入触发 `onLoad` + `onShow`,之后切换**只触发 `onShow`**(数据刷新放 `onShow`)
> 实测确认:产物 `app.json` 已包含完整 `tabBar` 配置与 4 个页面;
> 各页面 `usingComponents` 只包含自己用到的组件,按需引入正常。
- [ ] **补充 tabBar 图标(待办)**
当前为**纯文字 Tab**(`iconPath` 是可选字段,不带图标也能正常运行)。
微信要求图标为**本地图片**:≤ **40 KB**,建议 **81 × 81 px**,**不支持网络图片与字体图标**。
补齐方式:把图标放入 `src/static/tabbar/`(每个 Tab 需选中/未选中两张),
再在 `pages.json` 的 `tabBar.list` 各项目补上 `iconPath` 与 `selectedIconPath`。
- [x] **确认首页与标题** ✅
标题已由模板默认值 `uni-app` 改为实际业务名:工作台 / 任务 / 库存 / 我的;
`globalStyle` 兜底标题为 `WMS 小程序`。
**启动页由 `pages` 数组第一项决定**:第 6 节接入登录后,第一项已改为 `pages/login/login`
(登录 / 注册页),原 `pages/index/index` 退为第二个页面(tabBar 首页)。
原因:内部仓储工具必须登录后才能用,从登录页启动可避免首屏闪出工作台与未授权请求。
未登录访问其他页面由 `utils/auth-guard.ts` 的全局跳转拦截兜底。
- [x] **配置页面级启动模式(开发提效)** ✅
`src/pages.json` → `condition` 已配置 4 个编译模式,**仅开发期生效**。
微信开发者工具顶部「编译模式」下拉即可直达对应页面。
- [x] **约定页面生命周期用法** ✅(已在页面中示范)
- 页面级:`onLoad`(取参、初始化)、`onShow`(刷新数据)、`onReachBottom`(分页加载)、`onPullDownRefresh`(下拉刷新)
- 组合式 API 下从 `@dcloudio/uni-app` 引入对应 Hook
- 开启下拉刷新需同时设置 `enablePullDownRefresh: true` 并调用 `uni.stopPullDownRefresh()`
> `pages/task/task.vue` 示范了 `onLoad` 读路由参数 + `onShow` 刷列表;
> 各 tabBar 页的 `onShow` 已留好接口接入位置(第 5 节)。
- [ ] **列表性能**(待接口接入后落实)
长列表(如库存明细)使用 `scroll-view` + 虚拟列表,避免一次性渲染上千节点。
---
## 5. 网络请求
- [ ] **配置请求合法域名**
微信公众平台 → 开发管理 → 开发设置 → 服务器域名,配置 `request` / `uploadFile` / `downloadFile` 合法域名。
**必须 HTTPS**,且证书有效;域名不能使用 IP 或非标准端口。
- [x] **封装请求实例** ✅
位置:`src/utils/request.ts`(基于 `uni.request` 二次封装,行为对齐 new3 的 axios 封装)。
已覆盖:baseURL(`.env` 的 `VITE_APP_BASE_API`)、超时、`platform` / `project` 请求头、
`Authorization: Bearer <token>` 注入、响应头新 token 自动回写(续期场景)、
业务码判定(`code=1` 为成功)、错误码文案映射、401 / 50008 / 50012 / 50014 → 清登录态回登录页、
可选 `loading` 文案、失败统一 toast。
> 注:new3 里的 `isSystemApi` 标记在 Web 端**从未被消费**(死字段),未移植。
- [ ] **控制并发**
微信小程序 `wx.request` 并发上限 **10 个**,批量场景(如批量提交盘点)需自行排队或分批。
- [ ] **配置超时**
`src/manifest.json` → `networkTimeout`(`request` / `connectSocket` / `uploadFile` / `downloadFile`),默认 60000 ms(与微信对齐)。
- [ ] **弱网与异常兜底**
断网提示、请求重试、超时兜底文案;建议封装统一的错误提示(可复用 `uni.$u.toast`)。
---
## 6. 登录、鉴权与用户信息
- [x] **登录流程(账号密码版,对齐 new3)** ✅
启动页 `pages/login/login` → 组件 `components/login-panel/` →
`store/modules/user.ts` 的 `login()` → `api/user/user.ts` 的 `user.login`
(`POST /system?method=user.login&v=1.0&timestamp=...`,body `{ username, password, device }`)
→ 响应 `data.token` 写入 `utils/auth.ts`。
注册走同一网关的 `user.register`(`username` / `email` / `real_name` / `password`),
成功后回到登录页并回填账号(与 new3 一致,不自动登录)。
- [ ] **微信一键登录(`uni.login` → `user.loginByCode`)**
`uni.login` 取临时 `code` → 后端换 `openid` / `session_key` → 颁发业务 token。
本次未做:属独立链路,接口已具备(new3 有 `user.loginByCode`),后续按需补。
- [x] **token 与登录态** ✅
统一存于 `utils/auth.ts`(小程序无 Cookie,故用 `uni.getStorageSync`,key = `token`)。
token 失效由 `utils/request.ts` 统一兜底(清存储 → `reLaunch` 登录页)。
- [x] **未登录访问控制** ✅
`utils/auth-guard.ts` 用 `uni.addInterceptor` 拦截
`navigateTo` / `redirectTo` / `reLaunch` / `switchTab`,
未登录且目标非白名单时取消跳转并导向 `/pages/login/login?redirect=<来源页>`,
登录成功后自动回跳来源页。等价于 new3 的 `permission.ts` + `router.beforeEach`。
- [ ] **不要使用 `getUserProfile`**
该接口自 2022 年 10 月起已被微信回收,返回匿名数据。
获取头像昵称改用 **头像昵称填写能力**(`<button open-type="chooseAvatar">` + `<input type="nickname">`)。
- [ ] **手机号获取**
需通过 `<button open-type="getPhoneNumber">`,且账号需具备相应权限(通常需企业主体)。
---
## 7. 权限与隐私合规(提审重点)
- [ ] **梳理隐私接口清单**
涉及定位、相册、摄像头、麦克风、剪贴板、通讯录、蓝牙等的 API 需逐一确认。
仓储场景重点:**扫码(摄像头)、上传图片(相册/相机)、定位(如库位导航)、蓝牙打印**。
- [ ] **配置《小程序用户隐私保护指引》**
微信公众平台 → 设置 → 基本设置 → 服务内容声明 → 用户隐私保护指引,声明实际收集的信息类型。
未声明而调用隐私接口,会在真机上被拦截。
- [ ] **处理授权被拒的分支**
用户拒绝授权后应有降级方案与引导(引导至 `uni.openSetting` 重新开启),不能白屏或静默失败。
- [ ] **位置相关接口**
若使用定位,需在 `src/manifest.json` → `mp-weixin.permission` 中填写用途说明,
并在 `mp-weixin.requiredPrivateInfos` 中声明所用地理位置接口。
> 注意:位置权限描述配置在 **manifest** 中,**不是** `pages.json`(这是常见误区)。
- [ ] **后台能力声明**
如需后台播放音频等,配置 `mp-weixin.requiredBackgroundModes`。
- [ ] **合规红线**
不得诱导分享/关注、不得收集与业务无关的个人信息、不得使用未备案域名。
---
## 8. 样式与开发约定
- [ ] **尺寸单位统一用 `rpx`**(750 设计稿基准);`manifest.json` 的 `transformPx` 保持 `false`,不要依赖 px 自动转换。
- [ ] **品牌色与主题变量集中管理**
在 `src/uni.scss` 中覆盖 uview-plus 的 `$u-*` 变量(`theme.scss` 内变量均为 `!default`,放在文件末尾即可覆盖)。
⚠️ 严禁把 `uview-plus/index.scss` 引入 `uni.scss`(会破坏按需引入并导致包体积暴涨),它只能写在 `App.vue`。
- [ ] **组件统一使用 `up-` 前缀**
easycom 已配置 `^up-` / `^u--` / `^u-` 三条规则,推荐统一 `up-`,避免与 uni-app 内置组件(如 `u-slider`)重名冲突。
注意:修改 `easycom` 规则**不会热更新**,需重启编译。
- [ ] **自定义组件规范**
放 `src/components/组件名/组件名.vue` 才会被 easycom 自动扫描;
组件内样式默认隔离,跨组件需要穿透时用 `:deep()` 或 `styleIsolation` 相关配置。
- [ ] **条件编译**
平台差异逻辑用条件编译(`#ifdef MP-WEIXIN` / `#ifndef H5`),不要用运行时 `if` 判断平台。
- [x] **状态管理** ✅
已引入 Pinia(`pinia@2.1.7`)并在 `main.ts` 注册,登录态见 `store/modules/user.ts`。
⚠️ 两个实测要点:
1. **uni-app 小程序端 `createApp()` 必须把 `Pinia` 一并 `return`**,否则各页面拿到的不是同一实例;
2. 装 Pinia 需要 `--legacy-peer-deps`:`pinia@2.3+` 要求 Vue ≥ 3.5.11,
而 uni-app 锁定 `vue@3.4.21`;且 `vue-demi` 的可选 peer `@vue/composition-api`
会让 npm 误判为冲突。故选用 `pinia@2.1.7`。
---
## 9. 调试与测试
- [x] **开发调试流程** ✅(已实测走通)
`npm run dev:mp-weixin` → 微信开发者工具导入 `dist/dev/mp-weixin` 目录。
产物目录一旦导入过,后续编译会自动刷新,无需重复导入。
⚠️ **同一时间只能有一个 `dev:mp-weixin` 进程在跑**(已踩坑)
两个编译进程同时写 `dist/dev/mp-weixin` 会互相删除/覆盖对方的 chunk,
导致开发者工具点预览报:
`Error: ENOENT: no such file or directory, open '...\common\assets.js'`
> 识别技巧:**正常产物只有 `common/vendor.js`,根本不会生成 `common/assets.js`**。
> 只要看到报这个文件名,几乎就是产物写坏 / 历史残留。
排查与修复:
1. 查残留编译进程:
`Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -match 'dcloudio|uni\.js' } | Select ProcessId, CreationDate, CommandLine`
2. 杀掉多余进程 → 删除 `dist` → **只跑一个** `npm run dev:mp-weixin`
3. 注意:微信开发者工具的 `wxfilewatcher_x64.exe` 会锁住产物目录,
此时 `Remove-Item dist` 报「正由另一进程使用」是**正常现象**,不影响写入文件
验证产物完整性(比只看「构建成功」可靠得多):
扫描产物所有 `.js` 里的 `require("...")`,逐个确认目标文件存在,应为 **0 缺失**:
```powershell
$root="dist\dev\mp-weixin"; $missing=0; $total=0
Get-ChildItem $root -Recurse -File -Include *.js | ForEach-Object {
$f=$_; $c=Get-Content $f.FullName -Raw
foreach ($m in [regex]::Matches($c,'require\("([^"]+)"\)')) {
$total++
if (-not (Test-Path (Join-Path $f.DirectoryName $m.Groups[1].Value))) { $missing++ }
}
}
"引用 $total 个,缺失 $missing 个"
```
- [ ] **真机调试必做项**
授权弹窗、扫码、上传、扫码枪/蓝牙硬件、ios 与 android 差异、弱网表现。
- [ ] **隐私与授权前置验证**
在**未同意隐私协议**的干净账号下走一遍主流程,确认无接口被静默拦截。
- [ ] **真机 vs 模拟器差异**
部分能力(如 `backgroundColorContent`、分包预下载、部分隐私接口)模拟器表现与真机不一致,**以真机为准**。
- [ ] **构建前类型检查**
`npm run type-check`(vue-tsc)纳入提交前检查,避免类型错误进入仓库。
---
## 10. 发布上线流程
- [ ] **上传前自检**
- `setting.minified` 已开启、`urlCheck` 已恢复校验
- 已切换到正式环境接口地址与正式 AppID
- 已移除调试代码、`console.log`、测试入口页
- 主包/分包体积均未越线
- [ ] **版本管理**
`manifest.json` → `versionName`(如 1.0.0)/ `versionCode`(递增整数)
- [ ] **上传与提审**
微信开发者工具「上传」→ 公众平台「版本管理」→ 提交审核。
提审需填写:功能页面、测试账号、类目与资质、隐私指引。
- [ ] **审核常见驳回点**
- 隐私协议缺失或与实际收集信息不符
- 未提供可用的测试账号 / 测试路径
- 存在需登录才能看到任何内容但未提供账号
- 使用未备案或不可访问的接口域名
- [ ] **(可选)CI 自动化上传**
使用 `miniprogram-ci` 在流水线中自动上传,需在公众平台生成上传密钥。
- [ ] **发布后验证**
体验版验证 → 全量发布 → 线上巡检(登录、主流程、关键接口)
---
## 11. 接口与环境配置
- [x] **区分环境** ✅
已建 `.env.development`(`http://192.168.11.56:6060/`,与 new3 开发环境同一后端)
与 `.env.production`(`https://qimen.wms.gztbyc.com/`,⚠️ 上线前按实际情况确认)。
业务代码统一走 `import.meta.env.VITE_APP_BASE_API`。
> 实测验证:生产构建产物 `utils/request.js` 只含生产域名,开发地址未被混入。
> 待补:`.env.staging`(测试环境)暂未配置,需要时按同样方式新增即可。
- [ ] **禁止敏感信息入库**
密钥、私钥、上传密钥等一律不入 git;如需配置模板,提交 `.env.example` 而非真实 `.env`。
---
## 附录 A:常用命令
| 命令 | 作用 |
|---|---|
| `npm run dev:mp-weixin` | 开发编译(微信小程序),产物 `dist/dev/mp-weixin` |
| `npm run build:mp-weixin` | 生产构建(微信小程序),产物 `dist/build/mp-weixin` |
| `npm run dev:h5` | H5 开发调试 |
| `npm run build:h5` | H5 生产构建 |
| `npm run type-check` | 类型检查(vue-tsc) |
## 附录 B:关键文件职责速查
| 文件 | 职责 | 常改内容 |
|---|---|---|
| `src/pages.json` | 路由、窗口样式、tabBar、分包、easycom | 新增页面、分包、tabBar |
| `src/manifest.json` | 各端打包配置(`mp-weixin` 节点是微信端唯一来源) | AppID、setting、权限声明、平台优化项 |
| `src/App.vue` | 应用生命周期 + 全局样式 | uview-plus 基础样式引入 |
| `src/main.ts` | 应用实例创建 | 全局插件注册(UI、状态管理) |
| `src/uni.scss` | 全局 SCSS 变量 | 主题色、uview-plus 变量覆盖 |
## 附录 C:参考文档
- uni-app `pages.json`:https://uniapp.dcloud.net.cn/collocation/pages.html
- uni-app `manifest.json`:https://uniapp.dcloud.net.cn/collocation/manifest.html
- uview-plus 文档:https://uview-plus.jiangruyi.com
- 微信小程序开发文档:https://developers.weixin.qq.com/miniprogram/dev/framework/
- 微信小程序运营规范:https://developers.weixin.qq.com/miniprogram/product/
---
> 说明:本清单中标注 ✅ 的项已完成并经过实测验证;标注 ❌ 或未勾选的项待处理。
> 微信平台规则会不定期调整(尤其是隐私合规与审核规范),相关条目请以微信官方最新文档为准。