页面跳转
页面与页面之间跳转并传递参数
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
}