小程序获取路由参数方法封装
发布于 2 年前 作者 caigang 3070 次浏览 来自 分享

路由传参的几种场景:

1,小程序内普通跳转传参

直接获取
onLoad (options) {
  doSomething(options)
}

2,通过扫小程序码进入

文档:<a href="https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html" rel="noopener noreferrer" target="_blank">https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html</a>

通过扫小程序进入的时候,参数会被放在options.scene里
onLoad (options) {
  doSomething(decodeURIComponent(options.scene));
}

 

3,扫普通链接二维码打开小程序

文档:<a href="https://developers.weixin.qq.com/miniprogram/introduction/qrcode.html#%E4%BA%8C%E7%BB%B4%E7%A0%81%E8%B7%B3%E8%BD%AC%E8%A7%84%E5%88%99" rel="noopener noreferrer" target="_blank">https://developers.weixin.qq.com/miniprogram/introduction/qrcode.html\#%E4%BA%8C%E7%BB%B4%E7%A0%81%E8%B7%B3%E8%BD%AC%E8%A7%84%E5%88%99</a>

通过配置扫普通链接二维码打开小程序时,<span style="font-size: 16px;">参数会被放在options.q里</span>
onLoad (options) {
  doSomething(decodeURIComponent(options.q));
}

函数封装:

1,将params参数字符串转成对象返回

// 获取URL参数并转换成对象
const getQueryParams = (url) => {
  const sUrl = url.split('?');
  // 取最后一位,兼容全链接有?和纯参数无?
  const sParams = sUrl[sUrl.length - 1];
  const arr = sParams.split('&'); // ['a=1', 'b=2']
  const result = {};
  arr.forEach((item) => {
    const keyVal = item.split('=');
    // key值
    const key = keyVal.shift();
    // value值,兼容参数没encode时有=,例如'a=b=1' => [a, b, 1] => key: a,value: b=1
    const value = decodeURIComponent(keyVal.join('='));
    result[key] = value;
  })
  return result;
}

2,处理上述3种场景

const handleOptions = (options = {}, key) => {
  let params = JSON.parse(JSON.stringify(options));
  if (params.q || params.scene) {
    params = {
      ...params,
      ...getQueryParams(decodeURIComponent(params.q || params.scene)),
    }
  }
  if (key) {
    return params[key];
  } else {
    return params;
  }
}

3,使用

onLoad(options) {
 const params = handleOptions(options);
  doSomething(params);
// --------直接取某个key-------
  const id = handleOptions(options, id);
}
1 回复
回到顶部