移动端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

223 lines
3.9 KiB

---
1 week ago
description:
globs:
alwaysApply: false
---
1 week ago
# 智慧生态项目编码规范
## 代码风格
### JavaScript/Vue 规范
1. 使用 ES6+ 语法特性
2. 变量命名:
- 常量使用 UPPER_SNAKE_CASE
- 变量和函数使用 camelCase
- 组件名使用 PascalCase
3. 缩进使用 Tab 制表符
4. 字符串优先使用单引号
5. 语句末尾不加分号(遵循项目现有风格)
### Vue 组件规范
```vue
<template>
<view class="container">
<!-- 组件内容 -->
</view>
</template>
<script>
export default {
name: 'ComponentName',
data() {
return {
// 数据定义
}
},
onLoad() {
// uni-app 生命周期
},
methods: {
// 方法定义
}
}
</script>
<style lang="scss" scoped>
// 样式定义
</style>
```
## API 接口规范
### 接口定义示例
参考 [login.js](mdc:api/login.js) 的实现方式:
```javascript
import request from '@/utils/request'
// 登录方法
export function login(username, password, captchaVerification) {
const data = {
username,
password,
captchaVerification
}
return request({
url: '/system/auth/login',
headers: {
isToken: false
},
'method': 'POST',
'data': data
})
}
```
### 请求响应处理
1. 使用 [request.js](mdc:utils/request.js) 统一处理请求
2. 错误码定义在 [errorCode.js](mdc:utils/errorCode.js)
3. 统一的响应拦截和错误处理
## 状态管理规范
### Vuex Module 示例
```javascript
const state = {
// 状态定义
}
const mutations = {
SET_STATE(state, value) {
state.property = value
}
}
const actions = {
async fetchData({ commit }) {
const res = await api.getData()
commit('SET_STATE', res.data)
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
```
## 工具函数规范
### 工具函数定义
参考 [common.js](mdc:utils/common.js) 和 [ruoyi.js](mdc:utils/ruoyi.js):
1. 单一职责原则
2. 函数命名清晰
3. 添加必要的注释
## uni-app 特定规范
### 条件编译
```javascript
// #ifdef MP-WEIXIN
// 微信小程序特有代码
// #endif
// #ifdef APP-PLUS
// APP 特有代码
// #endif
```
### 页面跳转
使用 uni-app 的路由 API:
```javascript
// 保留当前页面,跳转到应用内的某个页面
uni.navigateTo({
url: '/pages/detail/detail'
})
// 关闭当前页面,跳转到应用内的某个页面
uni.redirectTo({
url: '/pages/index/index'
})
// 关闭所有页面,打开到应用内的某个页面
uni.reLaunch({
url: '/pages/login/login'
})
```
### 数据存储
使用 [storage.js](mdc:utils/storage.js) 封装的方法:
```javascript
import storage from '@/utils/storage'
// 存储
storage.set('key', value)
// 获取
const value = storage.get('key')
// 删除
storage.remove('key')
```
## 权限控制
### 路由权限
参考 [permission.js](mdc:permission.js) 实现:
1. 定义白名单页面
2. 使用拦截器进行权限验证
3. 未授权自动跳转登录页
### 接口权限
使用 [auth.js](mdc:utils/auth.js) 管理 Token:
```javascript
import { getAccessToken } from '@/utils/auth'
// 在请求头中携带 Token
const token = getAccessToken()
```
## 错误处理
### 统一错误提示
```javascript
uni.showToast({
title: '操作失败',
icon: 'none'
})
// 或使用封装的提示方法
this.$modal.msg('操作成功')
this.$modal.msgError('操作失败')
```
### 异常捕获
```javascript
try {
const res = await api.getData()
// 处理成功响应
} catch (error) {
console.error('请求失败:', error)
this.$modal.msgError('获取数据失败')
}
```
## 性能优化
### 小程序分包
1. 主包保持精简,只包含核心页面
2. 按功能模块进行分包
3. 在 [pages.json](mdc:pages.json) 中配置 subPackages
### 图片优化
1. 使用合适的图片格式
2. 控制图片大小
3. 使用懒加载
### 数据缓存
1. 合理使用本地存储
2. 避免频繁请求相同数据
3. 设置合理的缓存过期时间