在项目中,很多时候都要去获取路由中的参数去判断页面的登录状态,或者很多需要传参的时候,就直接获取 下面介绍我在项目中所用的2种方法:
1. 利用写好的一个函数,直接this.函数名去获取
GetUrlParameter (parameterName) {
var url = document.location.toString()
console.log(url)
var arrObj = url.split('?')
if (arrObj.length > 1) {
var arrPara = arrObj[1].split('&')
var arr
for (var i = 0; i < arrPara.length; i++) {
arr = arrPara[i].split('=')
if (arr != null && arr[0] === parameterName) {
return arr[1].replace('#', '').replace('/', '')
}
}
return ''
} else {
return ''
}
},
2.把地址栏的参数统一存在vuex,哪个页面用到就在本页面去获取
state: {
chl: sessionStorage.getItem("chl") ? sessionStorage.getItem("chl") : null,
shareUrl: sessionStorage.getItem("shareUrl") ? sessionStorage.getItem("shareUrl") : null, // 分享的地址
phone: sessionStorage.getItem("phone") ? sessionStorage.getItem("phone") : null
},
mutations: {
setUserInfo (state, {shareUrl, phone, isOrderedProduct, chl}) {
if (shareUrl) {
state.shareUrl = shareUrl
sessionStorage.setItem('shareUrl', shareUrl)
}
if (phone) {
state.phone = phone
sessionStorage.setItem('phone', phone)
}
if (chl) {
state.chl = chl
sessionStorage.setItem('chl', chl)
}
}
在本页面获取
// 动态获取地址栏的channelId
this.channelId = this.$store.state.chl
// 从路由获取phone
this.phone = this.$store.state.phone
this.shareUrl = this.$store.state.shareUrl
通过这样就不用几个页面之间相互去传参数,也比较麻烦,建议第二种方法,方便管理,存储数据。