小程序参数获取方式

页面跳转

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

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 小时前
Telegram 自动打包上传机器人 通过 Telegram 消息触发项目的自动打包和上传。
前端·机器人
4***14902 小时前
SpringSecurity登录成功后跳转问题
前端
小徐敲java2 小时前
window使用phpStudy在nginx部署前端测试
运维·前端·nginx
Winslei2 小时前
【hvigor专栏】OpenHarmony应用开发-hvigor插件之动态修改应用hap文件名
前端
扑棱蛾子2 小时前
前端代码一键打包上传服务器?10分钟配好永久告别手动部署!
前端·node.js
q***T5832 小时前
前端路由懒加载实现,React与Vue
前端·vue.js·react.js
灵犀坠2 小时前
前端开发核心知识:HTML5特性与经典面试题详解
前端·html·html5
Hilaku2 小时前
我为什么说全栈正在杀死前端?
前端·javascript·后端
8***B3 小时前
前端性能优化插件,图片懒加载与压缩
前端
木易士心3 小时前
Vue2 和 Vue3 中 watch 用法和原理详解
前端·vue.js