Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Methods for Passing Parameters in Mini Programs

Tech 1

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.

Tags: Mini Program

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.