小程序参数获取方式

页面跳转

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

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

接收参数

js 复制代码
// onLoad生命周期中获取
onLoad(options){
	console.log(options.age) // 12
	console.log(options.name) // tom
}

普通二维码

进入到微信小程序后台进行配置

扫描普通二维码打开小程序

获取参数

例如配置的小程序链接为:https://xxx/xxx?age=12&name=tom

js 复制代码
// 二维码链接内容会以参数 `q` 的形式带给页面,
// 微信传递进来会进行编码,需要进行decodeURIComponent解码
onLoad(options){
	const url = decodeURIComponent(options.q)
	console.log(url) // https://xxx/xxx?age=12&name=tom	
}

获取到的是完整的链接地址,我们需要通过?分隔,得到我们所需要的参数,改进上面代码。

js 复制代码
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'}
}

小程序码

生成小程序码

小程序码可以通过微信后台手动生成,也可以通过请求服务端接口进行生成

获取小程序码

获取参数

例如配置的二维码地址为:pages/demo?scene=12|tom

小程序码传递参数有格式限制,例如中文字符等,最好自行使用encodeURIComponent进行编码后传递

js 复制代码
// 微信传递进来会进行编码,需要进行decodeURIComponent解码
onLoad(options){
	const params = decodeURIComponent(options.scene)
	console.log(params) // 12|tom
}
相关推荐
锋行天下2 小时前
公司内网部署大模型的探索之路
前端·人工智能·后端
1024肥宅3 小时前
手写 EventEmitter:深入理解发布订阅模式
前端·javascript·eventbus
海市公约4 小时前
HTML网页开发从入门到精通:从标签到表单的完整指南
前端·ide·vscode·程序人生·架构·前端框架·html
行云流水6264 小时前
前端树形结构实现勾选,半勾选,取消勾选。
前端·算法
diudiu_335 小时前
web漏洞--认证缺陷
java·前端·网络
阿珊和她的猫5 小时前
<video>` 和 `<audio>` 标签的常用属性解析
前端
LSL666_5 小时前
4 jQuery、JavaScript 作用域、闭包与 DOM 事件绑定
前端·javascript·html
yinuo6 小时前
前端跨页面通讯终极指南⑤:window.name 用法全解析
前端
小飞侠在吗6 小时前
vue computed 和 watch
前端·javascript·vue.js
yinuo6 小时前
前端跨页面通讯终极指南④:MessageChannel 用法全解析
前端