需求代码总结
需求来源:本来只是做预交付的一个演示项目,没有登录页。因为数据和政府相关,网警说需要加验证,甲方需求得满足啊,这下项目经理头疼了,然后我就头疼了。
给我的原话是:把token拼接在地址里面,甲方通过一个加了token的网址才可以正常访问网页,我这边提取token进行校验。
第一反应,没听懂,为啥不直接加个登录页,万事大吉。经过多方沟通明白了,登录页也得要,token也得拼到地址栏。
因为甲方他有自己的网站,有自己的登录页,他们只是需要点击一个按钮或者链接就直接进入演示页面。而我们自己演示的时候,需要一个自己的登录页。
明白需求,开干!
1.首先更改路由配置
router-index.js
children: [
{
path: '/BaseProfile/:token',
name: 'BaseProfile',
component: () =>
import('@/views/screenDisplay/dzPage/BaseProfile'),
meta: {
title: '基地概况',
},
hidden: true
},
{
path: '/InternetMonitoring/:token',
name: 'InternetMonitoring',
component: () =>
import('@/views/screenDisplay/dzPage/InternetMonitoring'),
meta: {
title: '物联网监测'
},
hidden: true
},
{
path: '/diseaseControl/:token',
name: 'diseaseControl',
component: () =>
import('@/views/screenDisplay/dzPage/diseaseControl'),
meta: {
title: '病虫害防控'
},
hidden: true
},
]
添加路由守卫
router.beforeEach(function (to, from, next) {
//当访问路径有拼接token时
if(to.params.token){
//将token存储在本地,方便进行路由跳转
localStorage.setItem('tokenKey', to.params.token)
//验证token是否正确
ifToken(to.params.token).then((res) => {
if (res.body) {
//token正确,如果当前是登录页的话,直接跳转到首页
if(to.path == '/login'){
next('/BaseProfile/'+to.params.token)
}else{
next()
}
}
})
}else{
//如果没有token,进行登录页的跳转
if(to.path == '/login'){
next()
}else{
next('/login')
}
}
})
2.路由点击跳转页面也得改
<li class="first" :class="{ ActiveBtn: isActive == 0 }" @click="showActice(0)">
基地概况
</li>
<li class="first" :class="{ ActiveBtn: isActive == 1 }" @click="showActice(1)">
物联网监测
</li>
<li class="second" :class="{ ActiveBtn: isActive == 2 }" @click="showActice(2)">
病虫害防控
</li>
showActice(a) {
//获取本地保存的token
let tokenKey = localStorage.getItem('tokenKey')
this.isActive = a
if (a == 0) {
this.$router.push({
name: 'BaseProfile',
params: { token: tokenKey }
// query: { name: this.cityId, enterPriseId: this.enterPriseId },
})
} else if (a == 1) {
this.$router.push({
name: 'InternetMonitoring',
params: { token: tokenKey }
// query: { name: this.cityId, enterPriseId: this.enterPriseId },
})
} else {
this.$router.push({
name: 'diseaseControl',
params: { token: tokenKey }
// query: { name: this.cityId, enterPriseId: this.enterPriseId },
})
}
},
此时已经可以满足甲方需求了
3.完成我们公司自己的登录逻辑
login(data).then(res=>{
//其实也就是在登录成功路由跳转这里进行小变动,加个拼接的token
if(res.body){
this.$router.push('/BaseProfile/'+res.body.accessToken);
}
}
至此明白了,面向业务编程是怎么个事,学习路漫漫...
知识点总结
路由传参
//配置路由
children: [
{
path: '/BaseProfile/:token/:id',//用占位符声明接收params参数
name: 'BaseProfile',
component: () =>
import('@/views/screenDisplay/dzPage/BaseProfile'),
meta: {
title: '基地概况',
},
hidden: true
},
]
//传递参数
//to的字符串写法
<router-link :to="/BaseProfile/shshh/110">跳转</router-link>
//to的对象写法,当路由携带params参数时,若使用to的对象写法,则不能使用path配置项,需要使用name配置,不然参数就没了
<router-link :to="{
name:'BaseProfile',
params:{
token:'shsh',
id:222,
}
}">跳转</router-link>
//接收参数
$route.params.token
$route.params.id