UNIAPP 扫码路径 拼接错误 如何恢复(兼容小程序)
事例
小程序路径为:
http://xxx.xxx.xxx.xxx/url?id=1234567
需求
因为使用同一个二维码,想要uniapp H5版本也跳到相应的界面,页面路径为:
http://xxx.xxx.xxx.xxx/#/pages/code/code
提问
如何将id值传递过去并跳转相应的界面呢?
解决
首先,在pages.jso的数组第一列也就是根页面,/pages/index/index,拿到location.search
也就是 url?id=1234567 , 判断是否规定含有url,若存在,则
const str = location.search
if(str.indexOf("url") != -1 ) {
const index = str.indexOf("id")
let urlValue = str.slice(index)
urlValue = urlValue.replace("%3D","=")
uni.navigateTo({
url: "/pages/code/code?" + urlValue
})
location.assign(location.origin + "/" + location.hash)
return
}
location.assign是处理的重点,因为uniapp的跳转机制不做这样的处理会让浏览器的路径成为: http://localhost:3009/?url=id%3D1234567#/pages/code/code?id%3D1234567.
虽然程序仍旧可以使用,但那不是我们最终的诉求。
assign() 是js的一个方法,重新载入页面。