小程序頁面傳參數加密的案例:
封裝了一個url.js工具類,代碼:
// 構建urlconst buildURL = (url, query = {}, isSequence = true) => {
if (!query) return url
const joiner = url.match(/\?/) ? '&' : '?'
const queryStr = Object.keys(query)
.map(key => `${key}=${encodeURIComponent(isSequence ? JSON.stringify(query[key]) : query[key])}`)
.join('&')
return url + joiner + queryStr
}
// 解析query對象
const decodeQuery = (originQuery = {}, isSequence = true) => {
const result = {}
if (!originQuery) return {}
return Object.keys(originQuery).reduce((prev, curr) => {
result[curr] = decodeURIComponent(originQuery[curr])
if (isSequence) {
result[curr] = JSON.parse(result[curr])
}
return result
}, result)
}
module.exports = {
buildURL,
decodeQuery
}
傳遞時加密,大括號里面可以任意添加任何參數,在解密取值時在根據傳值取出來。代碼:
let url = app.urlHelper.buildURL('/pages/laugh/detail/index', {item: this.data.item
})
wx.navigateTo({
url,
})
使用時解密,在頁面onLoad方法中,添加代碼:
onLoad: function(options) {let item = app.urlHelper.decodeQuery(options).item
}