小程序獲取二維碼參數
生成二維碼的時候使用的是 wxacode.getUnlimited,接口 B(數量不受限制,參數較短)
文檔的截圖如下:
可以看到生成的二維碼的參數需要放在 scene
中
假設現在我們需要跳轉商品詳情,並且需要帶 2 個參數,一個商品 ID,一個店鋪 ID
則有: goodsId=1&storeId=2
然後在對應頁面使用 this.options.goodsId
和 this.options.storeId
來獲取對應參數即可
可是通過二維碼生成的鏈接並不能這樣獲取參數,打印
this.options
發現所有的參數都在
this.options.scene
中,並且已經通過urlencode
處理,說白了就是全部參數變成了字符串。這時候要獲取就不好操作了
下面說下怎麼獲取對應的參數
Page({
/**
* 生命週期函數--監聽頁面加載
*/
onLoad: function(options) {
if (options.scene) {
Object.assign(this.options, getScene(options.scene)) // 獲取二維碼參數,綁定在當前this.options對象上
}
console.log(this.options) // 這時候就會發現this.options上就會有對應的參數了
},
/**
* 獲取小程序二維碼參數
* @param {String} scene 需要轉換的參數字符串
*/
getScene: function(scene = "") {
if (scene == "") return {}
let res = {}
let params = decodeURIComponent(scene).split("&")
params.forEach(item => {
let pram = item.split("=")
res[pram[0]] = pram[1]
})
return res
}
})
主要是用到了 decodeURIComponent
解碼(這裏並不能直接獲得對象參數,只是把=被轉義的東西重新轉換回來)
然後在根據&
獲取每一個參數,獲取到每一個參數後,在通過循環,通過=
分割鍵值對
這樣就可以獲取小程序二維碼攜帶的參數了,並且獲取後放入到this.options
對象裏面,整個頁面都可以用