一文搞懂!小程序参数获取的 N 种秘籍

页面跳转

页面与页面之间跳转并传递参数

wx.navigateTo({
	url:'/pages/demo?age=12&name=tom'
})

接收参数

// onLoad生命周期中获取
onLoad(options){
	console.log(options.age) // 12
	console.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 才能获取到生成二维码时传入的 scene
	const params = decodeURIComponent(options.scene)
	console.log(params) // 12|tom
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值