Skip to main content
Version: Next

lmes-web-base State Management Scheme Detailed Document

Table of Contents​

  1. Introduction
  2. Project Structure Overview
  3. Core State Management Architecture
  4. Store.ts State Container Details
  5. State.ts Reactive State System
  6. globalState.ts Global State Management
  7. Inter-component State Passing Mechanism
  8. State Persistence Strategy
  9. Performance Optimization and Best Practices
  10. Error Handling and Debugging
  11. 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:

  1. System Config Initialization: Get system config via getSystemConfig() method
  2. Feature List: Get feature list via getFeatureList() method
  3. Work Section Data: Get product list via getProductList() method
  4. 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​

  1. 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
  2. Data serialization strategy:

    • Use JSON.stringify for serialization
    • Handle circular reference issues
    • Optimize storage space
  3. 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​

  1. State granularity control:

    • Avoid over-segmenting states
    • Reasonably divide state boundaries
    • Use composite states to reduce nesting
  2. Use of computed properties:

    • Utilize computed to cache calculation results
    • Avoid calling complex functions directly in templates
    • Reasonably use dependency tracking
  3. 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​

  1. API Call Error Handling:

    • Capture network exceptions
    • Handle server errors
    • Provide friendly error prompts
  2. State Update Error Handling:

    • Validate data format
    • Handle data transformation exceptions
    • Implement state rollback mechanism
  3. Component Render Error Handling:

    • Use ErrorBoundary to wrap components
    • Provide fallback UI
    • Record error logs

Debugging Best Practices​

  1. Development Environment Debugging:

    • Use Vue DevTools to monitor state changes
    • Enable detailed error stack information
    • Implement state snapshot function
  2. 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​

  1. Modern Architecture: Based on Vue 3 Composition API and reactivity system
  2. Modular Design: Clear state hierarchy and responsibility separation
  3. Performance Optimization: Multi-level performance optimization strategies and caching mechanisms
  4. Maintainability: Complete error handling and debugging tool support

Application Value​

  1. Complex Business Scenario Support: Suitable for complex business requirements of MES systems
  2. Cross-component Data Sharing: Efficient inter-component state passing mechanism
  3. State Persistence: Reliable local storage and data recovery capabilities
  4. Development Efficiency Improvement: Standardized state management processes and tools

Development Direction​

  1. State Management Tool Enhancement: Integrate more powerful debugging and monitoring tools
  2. Continuous Performance Optimization: Further optimize performance in large applications
  3. Type Safety Strengthening: Improve TypeScript type definitions and validation
  4. 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.