小程序页面传参数加密的案例:
封装了一个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
}