WeChat applet routing parameters

WeChat applet routing parameters

In the WeChat applet, data can be passed to the target page through routing parameters. Here's a common way:

In the source page, use wx.navigateTothe or wx.redirectTomethod to jump to the target page, and pass data through URL parameters. Example:

wx.navigateTo({
    
    
  url: 'targetPage?param1=value1&param2=value2'
});

In the onLoadlifecycle , optionsthe passed parameters can be obtained through the parameter. Example:

onLoad: function(options) {
    
    
  const param1 = options.param1;
  const param2 = options.param2;
  console.log(param1); // 输出: value1
  console.log(param2); // 输出: value2
}

Data can be passed between pages by adding parameters to the URL and getting those parameters in onLoadfunctions .

Note: If you use wx.redirectTothe method to jump to the page, the target page will replace the current page without retaining the original page in the page stack. However, using wx.navigateTothe method to jump will push the target page into the page stack, and return to the original page when returning. Choose the appropriate jump method according to your specific needs.

What if the parameter to be passed is an object?

If the parameter to be passed is an object, routing parameters can be passed in the following ways in the WeChat applet:

In the source page, use wx.navigateTothe or wx.redirectTomethod to jump to the target page, and convert the object parameter into a string form for passing. Example:

const objParam = {
    
     key1: 'value1', key2: 'value2' };
const encodedParam = encodeURIComponent(JSON.stringify(objParam));
wx.navigateTo({
    
    
  url: 'targetPage?param=' + encodedParam
});

In onLoadthe lifecycle , optionsobtain the passed parameters through the parameter, and parse the string parameter into an object form. Example:

onLoad: function(options) {
    
    
  const encodedParam = options.param;
  const decodedParam = JSON.parse(decodeURIComponent(encodedParam));
  console.log(decodedParam.key1); // 输出: value1
  console.log(decodedParam.key2); // 输出: value2
}

In the above example, we first use JSON.stringify()the method into a string form, and encodeURIComponent()encode it through . In onLoadthe function , we first use decodeURIComponent()to decode, and then use JSON.parse()the method to parse the string into an object to obtain the original parameter object.

Note that in actual use, for complex object parameters, it is necessary to ensure that the object can be correctly converted into a string form, and properly parsed and processed in the target page.

Guess you like

Origin blog.csdn.net/weixin_55020138/article/details/130722900