开发日志:微信小程序太阳码传入参数解析

通过二维码进入小程序的时候,可以在 onload 函数里面获取参数。

onLoad(options) {
    
    
	console.log(options)
}

这个是打印出来的结果。所以,在这里我们需要用到的是 options.scene。
传入的原始数据

第一步,使用 decodeURIComponent 解析一下,就可以得到传入的参数。

post_id=74413&category_id=360

但这是字符串,不方便后面的取值、存值。

第二步,可以将 options.scene 里面的普通字符串拼接修改成 json 字符串,再使用 JSON.parse 转换成对象。
最后获得的结果
这样就变成方便操作的数据了。

合起来就是: 在需要获取参数的地方,调用函数 this.sceneToObj() 就可以了

onLoad(options) {
    
    
	if (options.scene) {
    
      // 扫码进来
		let query = this.sceneToObj(options.scene)
        this.setData({
    
    
        	postID: query.post_id || '',
        	categoryID: query.category_id || ''
        })
    }
},
sceneToObj(str) {
    
    
	const scene = decodeURIComponent(str)
	let str1 = scene.replace(/=/g, '":')
	let str2 = str1.replace(/&/g, ',"')
	let obj = JSON.parse('{"' + str2 + '}')
	return obj
}

猜你喜欢

转载自blog.csdn.net/qq_37992222/article/details/112198531