methods: {
login() {
post("/login", this.infor).then(
(res) => {
sessionStorage.setItem("infor", JSON.stringify(res.infor));
this.$router.addRoutes(asyncRoutes); //asyncRoutes是我自己另写的路由表
sessionStorage.setItem("asyncRoutes",JSON.stringify(asyncRoutes))
this.$router.push("/index");
},
(res) => {
console.log(res);
}
);
},
},
//上面是我登录后添加的动态路由
const routes = [
{
path: '/login',
name: 'Login',
component: () => import("../views/Login")
},
{
path: '*',
name: '404',
component: () => import("../views/404")
}
]
const router = new VueRouter({
mode: 'history',
routes
})
// 全局导航守卫
router.beforeEach((to, from, next) => {
console.log(to, from)
if (getToken()) { //判断有没有token
if (to.path == "/login") {
next(from.path)
} else {
next()
}
} else {
if (to.path == "/login") {
next()
} else {
next("/login")
}
}
})
<el-menu
:default-active="activeIndex"
class="el-menu-demo headers"
mode="horizontal"
@select="handleSelect"
>
<router-link v-for="(item,index) in routers" :key="index" :to="item.path">
<el-menu-item :index="item.showOrder.toString()" class="el-item">
<img :src="'/user/'.concat(item.iconCls)" alt />
<div class="titlename">{{item.title}}</div>
</el-menu-item>
</router-link>
</el-menu>
这是我的一个element 的menu菜单,类似登录后的二级菜单栏
然后组件自带一个select的事件,你可以认为是点击事件
select菜单激活回调index: 选中菜单项的 index, indexPath: 选中菜单项的 index path(这是element-ui的官网形容)
default-active当前激活菜单的 index string
然后我的data里面有一个参数接收
data() {
return {
activeIndex: "",
};
},
选中之后的handleSelect的回调函数
methods: {
handleSelect(key) {
this.activeIndex = key;
sessionStorage.setItem("tab", JSON.stringify(key));
},
}
直接把当前路由存在sessionStorage里面
mounted() {
// 刷新页面tab不会切换到第一个
let list = JSON.parse(sessionStorage.getItem("tab"));
if (list) {
this.activeIndex = list;
}
},
然后每次加载页面 就是mounted 生命函数,判断当前路由路径是不是存的那个,然后直接赋值就完事儿了,或者直接使用router 的push就可以,大概思路,具体的
还有你的.then写多了把还是你自己二次封装过了
若果是axios应该是
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
然后你请求成功了之后 this.$router.push("/index");
你的路由表里面也有有 “/index” 的路由哇
如果你是用的Nginx,那么可以在location / {}中加入try_files $uri $uri/ /index.html;
全局守卫那边to和from是不是写反了,to是接下来要跳转的那个页面,from是从哪个页面跳转,指上一个页面
如果是部署问题我这边文章写的很详细,[vue-cli 打包之后的各种部署问题集中地](https://blog.csdn.net/alnorthword/article/details/110284085?spm=1001.2014.3001.5502)
开发环境的话,刷新不会有问题的
是刷新导致动态路由丢了,可以在根组件或者入口点文件判断你动态路由是否存在,不存在的话从本地再次添加进去
您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632
我昨天刚解决得这个问题,别用beforeEach了,用
router.onReady(() => { // 页面刷新 重新加载动态路由 在这里重新加一下已经把保存得路由就行了 router.addRoutes(userRouters) })
参考:https://mp.csdn.net/editor/html/115351275
需要在App.vue文件写一遍获取路由表,然后 this.$router.addRoutes(asyncRoutes);