一文搞懂!小程序参数获取的 N 种秘籍_微信小程序获取页面参数
页面跳转
页面与页面之间跳转并传递参数
wx.navigateTo({url:\'/pages/demo?age=12&name=tom\'})
接收参数
// onLoad生命周期中获取onLoad(options){console.log(options.age) // 12console.log(options.name) // tom}
普通二维码
进入到微信小程序后台进行配置
扫描普通二维码打开小程序
获取参数
例如配置的小程序链接为:https://xxx/xxx?age=12&name=tom
// 二维码链接内容会以参数 `q` 的形式带给页面,获取时需自行 `decodeURIComponent` 一次onLoad(options){const url = decodeURIComponent(options.q)console.log(url) // https://xxx/xxx?age=12&name=tom}
获取到的是完整的链接地址,我们需要通过?
分隔,得到我们所需要的参数,改进上面代码。
const queryURLParams = (url: string) => { const pattern = /(\\w+)=(\\w+)/gi; //定义正则表达式 const parames: Record<string, any> = {}; // 定义参数对象 url.replace(pattern, ($, $1, $2) => { parames[$1] = $2; return \"\"; }); return parames;};onLoad(options){const url = decodeURIComponent(options.q)const params = queryURLParams(url) // {age:12,name:\'tom\'}}
小程序码
生成小程序码
携带的参数会以scene
字段的形式带入到页面中
1.微信小程序后台生成
比如我们配置的地址为:pages/demo?scene=12|tom
2.服务端接口生成
获取小程序码
例如参数格式:
{page:\'pages/demo\',scene:\'12|tom\'}
这种方式传递的 scene有格式限制
最大32个可见字符,只支持数字,大小写英文以及部分特殊字符:!#$&\'()*+,/:;=?@-._~,其它字符请自行编码为合法字符(因不支持%,中文无法使用 urlencode 处理,请使用其他编码方式)
3开发工具调试
调试阶段可以使用开发工具的条件编译自定义参数 scene=xxxx 进行模拟,开发工具模拟时的 scene 的参数值需要进行 encodeURIComponent
获取参数
小程序码传递参数有格式限制,例如中文字符等,可以使用
encodeURIComponent
进行编码后传递
onLoad(options){// scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 sceneconst params = decodeURIComponent(options.scene)console.log(params) // 12|tom}