- API 路由统一: 移除 /api/h5/,统一 /api/pms/ 入口 - 二进制改名: api-server -> pms-api(与服务名一致) - nginx: 合并 /api/ + /pms/api/ 为 /api/pms/ - 新增 docs/API.md 接口文档 - 后端: CabinetDetail 增加 rssi/pow_fail/address/soc 等字段 - Redis 管道批量读取仓体实时数据(SOC/电压/电流/功率) - DB: 所有 TIMESTAMP 列改为 DATETIME(修复类型不匹配) - 用户管理: 新增创建时间/修改时间列,状态改用 Switch - 角色管理/用户管理: 操作按钮改为图标 - PC 设备详情: 基本信息补全 RSSI/ICCID/电源/地址 - PC 卡片: 通道统计改用 Lucide 图标,颜色统一 - PC 二维码: canvas 渲染,含编号文字,支持右键下载 - H5: 按 uni-app 规范修正导航(navigateTo 替代 reLaunch) - H5: 详情页加返回导航条 - H5: 扫码支持摄像头(jsQR)+ ?id= 参数 - H5: 底部 tabBar 在所有页面常显 - H5: 首页统计改为 6 项(设备/通道/空闲/充电/充满/故障) - H5: 下拉刷新 / 上拉加载 - 产品首页: 添加业务联系 - 文档: 清理过时文件,补充缺失规范章节
5.9 KiB
5.9 KiB
title, impact, impactDescription, type, tags
| title | impact | impactDescription | type | tags | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Return State as Readonly with Explicit Update Methods | MEDIUM | Exposing mutable state directly allows uncontrolled mutations scattered throughout the codebase | best-practice |
|
Return State as Readonly with Explicit Update Methods
Impact: MEDIUM - When a composable manages state that should only be modified in controlled ways, return the state as readonly and provide explicit methods for updates. This prevents scattered, uncontrolled mutations and makes state changes traceable and predictable.
Exposing raw refs allows any consumer to modify state directly, leading to bugs that are hard to track because mutations can happen anywhere in the codebase.
Task Checklist
- Use
readonly()to wrap state that shouldn't be directly modified - Provide explicit methods for all valid state transitions
- Document the intended ways to update state
- Consider returning
shallowReadonly()for performance with large objects
Incorrect:
// WRONG: State is fully mutable by any consumer
export function useCart() {
const items = ref([])
const total = computed(() =>
items.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
)
return { items, total } // Anyone can mutate items directly!
}
// Consumer code - mutations scattered everywhere
const { items, total } = useCart()
// In component A
items.value.push({ id: 1, name: 'Widget', price: 10, quantity: 1 })
// In component B - different mutation pattern
items.value = items.value.filter(item => item.id !== 1)
// In component C - direct modification
items.value[0].quantity = 5
// Hard to track: where did this item come from? Why did quantity change?
Correct:
import { ref, computed, readonly } from 'vue'
export function useCart() {
const items = ref([])
const total = computed(() =>
items.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
)
const itemCount = computed(() =>
items.value.reduce((sum, item) => sum + item.quantity, 0)
)
// Explicit, controlled mutations
function addItem(product, quantity = 1) {
const existing = items.value.find(item => item.id === product.id)
if (existing) {
existing.quantity += quantity
} else {
items.value.push({ ...product, quantity })
}
}
function removeItem(productId) {
const index = items.value.findIndex(item => item.id === productId)
if (index > -1) {
items.value.splice(index, 1)
}
}
function updateQuantity(productId, quantity) {
const item = items.value.find(item => item.id === productId)
if (item) {
item.quantity = Math.max(0, quantity)
if (item.quantity === 0) {
removeItem(productId)
}
}
}
function clearCart() {
items.value = []
}
return {
// State is readonly - can't be mutated directly
items: readonly(items),
total,
itemCount,
// Only these methods can modify state
addItem,
removeItem,
updateQuantity,
clearCart
}
}
// Consumer code - controlled mutations only
const { items, total, addItem, removeItem, updateQuantity } = useCart()
// items.value.push(...) // TypeScript error: readonly!
// items.value = [] // TypeScript error: readonly!
// Correct way - through explicit methods
addItem({ id: 1, name: 'Widget', price: 10 })
updateQuantity(1, 3)
removeItem(1)
Pattern: Internal vs External State
Keep internal state private, expose readonly view:
export function useAuth() {
// Internal, fully mutable
const _user = ref(null)
const _token = ref(null)
const _isLoading = ref(false)
const _error = ref(null)
async function login(credentials) {
_isLoading.value = true
_error.value = null
try {
const response = await api.login(credentials)
_user.value = response.user
_token.value = response.token
} catch (e) {
_error.value = e.message
throw e
} finally {
_isLoading.value = false
}
}
function logout() {
_user.value = null
_token.value = null
}
return {
// Readonly views of internal state
user: readonly(_user),
isAuthenticated: computed(() => !!_user.value),
isLoading: readonly(_isLoading),
error: readonly(_error),
// Methods for state changes
login,
logout
}
}
When to Use readonly vs Not
Use readonly |
Don't Use readonly |
|---|---|
| State with specific update rules | Simple two-way binding state |
| Shared state between components | Form input values |
| State that needs validation on change | Local component state |
| When debugging mutation sources matters | When consumers need full control |
// Form input - consumers SHOULD mutate directly
export function useForm(initial) {
const values = ref({ ...initial })
return { values } // No readonly - it's meant to be mutated
}
// Counter with min/max - needs controlled mutations
export function useCounter(min = 0, max = 100) {
const _count = ref(min)
function increment() {
if (_count.value < max) _count.value++
}
function decrement() {
if (_count.value > min) _count.value--
}
return {
count: readonly(_count),
increment,
decrement
}
}
Performance: shallowReadonly
For large objects, use shallowReadonly to avoid deep readonly conversion:
export function useLargeDataset() {
const data = ref([/* thousands of items */])
return {
// shallowReadonly - only top level is readonly
// Nested properties are still technically mutable
// but the ref itself can't be reassigned
data: shallowReadonly(data)
}
}