lmes-web-base State Management Scheme Detailed Document
Table of Contents
- Introduction
- Project Structure Overview
- Core State Management Architecture
- Store.ts State Container Details
- State.ts Reactive State System
- globalState.ts Global State Management
- Inter-component State Passing Mechanism
- State Persistence Strategy
- Performance Optimization and Best Practices
- Error Handling and Debugging
- Conclusion
Introduction
lmes-web-base adopts a global state management scheme based on Vue 3 Composition API and custom Store modules. This scheme provides an efficient and maintainable state management solution for complex MES (Manufacturing Execution System) applications through reactive state systems, provide/inject mechanisms, and modular design.
Core features of this state management scheme include:
- Modern state management based on Vue 3 reactivity system
- Modular state organization
- Support for state persistence and cross-page data sharing
- Efficient inter-component state passing mechanism
- Comprehensive performance optimization strategies
Project Structure Overview
Diagram sources
Core State Management Architecture
The state management architecture of lmes-web-base adopts a layered design, forming a complete state management system from the underlying reactive basis to the top-level business components.
Diagram sources
Section sources
Store.ts State Container Details
Store.ts is the core of the entire state management scheme. It is responsible for creating global state containers, managing state lifecycles, and providing state access interfaces.
State Container Initialization
// Base state generator
const baseDataGenerate = (key?: BaseKeyEnum) => {
const data: BaseState = {
systemConfig: { state: ref({}) },
workSectionList: { state: ref([]) },
featureList: { state: ref([]) },
featureMap: { state: ref({}) },
}
return key ? data[key] : data
}
Global State Hook Function
export const useGlobalState = createGlobalState<{
systemConfig: StateRef
workSectionList: StateRef
featureList: StateRef
productionLineList: StateRef
hasProductionLine: Ref<boolean>
getSystemConfig: () => Promise<any>
getWorkSectionList: (segmentId?: string) => Promise<any>
}>()
Async State Initialization Flow
Diagram sources
State Update Mechanism
Store.ts implements a complete asynchronous state update mechanism, supporting initialization and update from multiple data sources:
- System Config Initialization: Get system config via
getSystemConfig()method - Feature List: Get feature list via
getFeatureList()method - Work Section Data: Get product list via
getProductList()method - Work Station List: Get work station info via
getWorkStationList()method
Section sources
State.ts Reactive State System
State.ts provides a lightweight local state management system, specifically for handling component internal state persistence needs.
Local State Persistence
// State key name
const StateKey = Symbol('state').toString()
// Restore state from localStorage
const stateStr = localStorage.getItem(StateKey) || '{}'
let initValue = {}
try {
initValue = JSON.parse(stateStr)
} catch (error) {
console.error(error)
}
// Reactive state
export const state = ref<Record<string, any>>(initValue)
Automatic State Persistence
// Watch state changes and automatically save to localStorage
watch(
state,
(v) => {
if (Object.keys(state.value).length) {
localStorage.setItem(StateKey, JSON.stringify(v))
}
},
{ deep: true }
)
Component State Provide/Inject Pattern
Diagram sources
Section sources
globalState.ts Global State Management
globalState.ts provides a simple global reactive state container as a supplement to Store.ts, used for handling simple states that do not require complex logic.
Global State Container
import { reactive, onMounted, ref, Ref } from 'vue'
export const globalState = reactive({})
Although simple in implementation, globalState plays an important role in the following scenarios:
- Temporary state storage
- Simple data sharing across components
- As a backup state container for Store.ts
Collaboration with Store.ts
Diagram sources
Section sources
Inter-component State Passing Mechanism
lmes-web-base adopts Vue 3's provide/inject mechanism combined with custom state management to achieve efficient inter-component state passing.
BaseTable State Management Pattern
// State Provider
export const createState = (props: TablePropsItemType, ctx: SetupContext) => {
store = useStore(props, ctx)
provide(KEY, store)
return store as StoreType
}
// State Consumer
export const injectState = () => {
const injectStore = inject(KEY, '')
if (!injectStore) {
return store as StoreType
}
return inject(KEY) as StoreType
}
State Passing Flow
Diagram sources
Actual Usage Example
Using global state in ConsoleManagement component:
// Usage example in Header.tsx
const { systemConfig } = useGlobalState()
const hasProduct = computed(() => {
return systemConfig.state.value?.ProductionLineStructure == 1
})
Using global state in OrderManagement component:
// Usage example in PlanSegmentDialog.tsx
const { getProductList, productionLineList } = useGlobalState()
const onOpen = async () => {
getProductList()
// Other initialization logic
}
Section sources
State Persistence Strategy
lmes-web-base implements a multi-level state persistence strategy to ensure user data remains available after page refresh.
Local Storage Strategy
// Storage tools provided by storage.ts
const Local = {
set(key: string, val: any) {
window.localStorage.setItem(key, JSON.stringify(val))
},
get(key: string) {
const value: null | string = window.localStorage.getItem(key) || null
if (!value) return null
return JSON.parse(value)
},
remove(key: string) {
window.localStorage.removeItem(key)
},
clear() {
window.localStorage.clear()
},
}
const Session = {
set(key: string, val: any) {
window.sessionStorage.setItem(key, JSON.stringify(val))
},
get(key: string) {
const value: null | string = window.sessionStorage.getItem(key)
try {
if (!value) return null
return JSON.parse(value)
} catch (error) {
return value
}
},
remove(key: string) {
window.sessionStorage.removeItem(key)
},
clear() {
window.sessionStorage.clear()
},
}
State Persistence Flow
Diagram sources
Persistence Best Practices
-
Choose appropriate storage method:
- localStorage: Suitable for long-term storage of configuration info
- sessionStorage: Suitable for temporary session data
- Memory state: Suitable for temporary calculation results
-
Data serialization strategy:
- Use JSON.stringify for serialization
- Handle circular reference issues
- Optimize storage space
-
Version compatibility:
- Add data format version number
- Implement data migration logic
- Handle data format changes
Section sources
Performance Optimization and Best Practices
The state management scheme of lmes-web-base adopts various strategies in performance optimization to ensure efficient operation in large applications.
Computed Property Optimization
// Use computed to optimize conditional judgment
const hasProductionLine = computed(() => {
const state: Ref<any> = systemConfig.state
const structure = state.value.ProductionLineStructure
return structure == 1
})
// Use computed to optimize data transformation
const dataSourceMap = computed(() => {
const map = new Map<string, any>()
for (const item of dataSource.value) {
map.set(item[rowId.value], item)
}
return map
})
Async Operation Optimization
// Debounce processing to prevent frequent requests
const getSystemConfig = async (checked: boolean = false) => {
const fn = async () => {
const data = await getFormDataBySettings()
systemConfig.state.value = data || config
}
// Use setTimeout to avoid repeated requests
return new Promise<void>((resolve) => {
const getConfig = async () => {
const condition = systemSetTimeT !== oldSystemSetTimeT && !checked
oldSystemSetTimeT = systemSetTimeT
if (condition) {
await handleCheckedState()
resolve()
} else {
await awaitInitLoading()
resolve()
}
systemSetTimeT && clearTimeout(systemSetTimeT)
}
systemSetTimeT = setTimeout(getConfig, 100)
})
}
Memory Management Optimization
Best Practice Suggestions
-
State granularity control:
- Avoid over-segmenting states
- Reasonably divide state boundaries
- Use composite states to reduce nesting
-
Use of computed properties:
- Utilize computed to cache calculation results
- Avoid calling complex functions directly in templates
- Reasonably use dependency tracking
-
Async operation management:
- Use debounce and throttle
- Implement request deduplication
- Add timeout and retry mechanisms
Section sources
Error Handling and Debugging
lmes-web-base implements a complete error handling mechanism and debugging tool integration to ensure system stability and maintainability.
Error Handling Strategy
// Exception capture and handling
const getWorkSectionList = async (segmentId?: string) => {
const params: Record<string, any> = {
MaxResultCount: 999,
SkipCount: 0,
}
if (segmentId) {
params.Segment = segmentId
}
try {
const res = await getWorkSectionApi(params)
const items = res.items.map((v) => {
return {
label: v.name,
value: v.id,
workSectionCode: v.code,
source: { ...v },
}
})
if (!segmentId) {
workSectionList.state.value = items || []
}
return items
} catch (error) {
console.error('Failed to get work section list:', error)
return []
}
}
State Debugging Tools
Error Boundary Handling
-
API Call Error Handling:
- Capture network exceptions
- Handle server errors
- Provide friendly error prompts
-
State Update Error Handling:
- Validate data format
- Handle data transformation exceptions
- Implement state rollback mechanism
-
Component Render Error Handling:
- Use ErrorBoundary to wrap components
- Provide fallback UI
- Record error logs
Debugging Best Practices
-
Development Environment Debugging:
- Use Vue DevTools to monitor state changes
- Enable detailed error stack information
- Implement state snapshot function
-
Production Environment Monitoring:
- Implement error reporting mechanism
- Monitor key state metrics
- Provide state recovery function
Section sources
Conclusion
The state management scheme of lmes-web-base is a well-designed, fully functional state management system with the following core advantages:
Technical Features
- Modern Architecture: Based on Vue 3 Composition API and reactivity system
- Modular Design: Clear state hierarchy and responsibility separation
- Performance Optimization: Multi-level performance optimization strategies and caching mechanisms
- Maintainability: Complete error handling and debugging tool support
Application Value
- Complex Business Scenario Support: Suitable for complex business requirements of MES systems
- Cross-component Data Sharing: Efficient inter-component state passing mechanism
- State Persistence: Reliable local storage and data recovery capabilities
- Development Efficiency Improvement: Standardized state management processes and tools
Development Direction
- State Management Tool Enhancement: Integrate more powerful debugging and monitoring tools
- Continuous Performance Optimization: Further optimize performance in large applications
- Type Safety Strengthening: Improve TypeScript type definitions and validation
- Ecosystem Extension: Support integration of more third-party state management libraries
This state management scheme provides a solid technical foundation for lmes-web-base, capable of meeting the business needs of complex MES systems while maintaining good maintainability and extensibility. Through reasonable architecture design and application of best practices, it ensures the long-term stable operation and continuous development of the system.