小程序参数获取方式

页面跳转

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

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
}
相关推荐
万少7 分钟前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站2 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名5 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫5 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊5 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter5 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折5 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_6 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial6 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu6 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端