Methods for Passing Parameters in Mini Programs
Data can be shared across pages in a mini program by setting properties on the global App instance. This instance holds a globalData object which acts as a global state container.
// app.js
App({
globalData: {
userProfile: null
}
})
Other pages can retrieve this app instance using getApp() and then access or modify the globalData.
// In any page script
const appInstance = getApp()
console.log(appInstance.globalData.userProfile)
appInstance.globalData.userProfile = { username: 'Alex', userId: 25 }
While convenient for sharing data, careful management of the global state's scope and lifecycle is necessary to avoid unintended side effects.
Using Locall Storage for Parameter Passing
For more persistent or secure data passing, the mini program's local storage APIs (wx.setStorage, wx.getStorage) can be used. Data is written to and read from the device's local cache.
// Page A: Store data
wx.setStorage({
key: 'userToken',
data: 'abc123xyz'
})
// Page B: Retrieve data
wx.getStorage({
key: 'userToken',
success(res) {
console.log(res.data) // Outputs: abc123xyz
}
})
Synchronous versions of these methods (wx.setStorageSync, wx.getStorageSync) are also available. This method is suitable for larger or sensitive data, but developers must be mindful of storage quotas and data security to prevent leaks or tampering.
Event-Based Parameter Passing
Custom components can communicate with their parent pages or other components by triggering events with triggerEvent. Parameters are passed within the event detail.
// Inside a custom component
this.triggerEvent('statusChange', { newStatus: 'active', timestamp: Date.now() })
// In the parent page's WXML, listening for the event
<my-component bind:statusChange="onStatusUpdate" />
// The event handler in the parent page's JS
onStatusUpdate: function(event) {
console.log(event.detail.newStatus) // Outputs: active
}
Passing Data via the Page Stack
When navigating between pages, data can be passed via the URL's query string or through the event channel API for backward navigation.
// Navigate forward with URL parameters
wx.navigateTo({
url: '/pages/product/product?id=P1001&category=electronics'
})
// Navigate back and pass data via event channel
wx.navigateBack({
delta: 1,
success(res) {
const eventChannel = this.getOpenerEventChannel()
eventChannel.emit('dataFeedback', { confirmed: true, orderId: 'ORD789' })
}
})
Real-Time Data Transfer with WebSocket
For real-time, bidirectional communication, WebSocket connections can be established. This is ideal for live updates, chat, or collaborative features.
// Establish a WebSocket connection
wx.connectSocket({
url: 'wss://api.example.com/ws'
})
// Send a message through the socket
wx.sendSocketMessage({
data: JSON.stringify({ action: 'ping', value: 1 }),
success() {
console.log('Message sent successfully')
}
})
Key Considerations for Parameter Passing
Data Size Limits: Different methods have different constraints. URL query strings typically have a size limit (e.g., 2KB), while Storage and global variables can handle larger payloads.
Security: When transmitting sensitive data, always use secure protocols like WSS for WebSockets and ensure API endpoints use HTTPS.
Data Type Conversion: Parameters passed via URLs are inherently strings. Explicit type conversion (e.g., Number(), JSON.parse()) is often required in the receiving page.
Page Lifecycle Impact: When passing data through the page stack, timing is crucial relative to page lifecycle events (onLoad, onShow). Incorrect timing can lead to stale data, unnecessary re-renders, or lifecycle method duplication.
Comparison of Methods
URL Query Parameters: Simple and direct, but limited in data capacity and exposed in the navigasion path.
Global Variables (globalData): Efficient for app-wide state sharing, but lacks persistence and requires careful state management to avoid pollution.
Local Storage: Provides persistence and larger capacity, suitable for non-volatile data, with the overhead of asynchronous I/O operations.
Custom Events: Excellent for decoupled communication between components and their parent pages, but limited to hierarchical relationships.
WebSocket: Enables real-time, full-duplex communication, essential for interactive features, but introduces backend complexity and connection management overhead.