【前端问题库】[vue-router] router.addRoutes() is deprecated and has been removed in Vue Router
[vue-router] router.addRoutes() is deprecated and has been removed in Vue Router 4. Use router.addRoute() instead.
·
问题: [vue-router] router.addRoutes() is deprecated and has been removed in Vue Router 4. Use router.addRoute() instead.
问题截图:
讨论:
- 动态添加路由报错
解决办法:
router.addRoutes()
在vue3
弃用,需要用router.addRoute()
- 多个路由具体写法(一般用法):
dynamicRoutes.forEach(res=>{
router.addRoute(res);
})
- 路径修改(实例一)
修改之前:
修改之后:
- 路径修改(实例二)
修改之前(vue2):
export default function (router) {
router.beforeEach((to, from, next) => {
let userName = store.state.permission.user.name;
let role = store.state.permission.user.role;
let token = store.state.permission.user.token;
if (userName && token) {
// 已登录并获取到用户角色等状态
if (to.path === '/login') {
next();
} else {
if (!store.state.permission.matched) {
// 若未处理用户的路由访问权限,则进行如下处理
store.dispatch('permission/GenerateRoutes', role).then(() => {
let routers = store.state.permission.routers;
// addRoutes 数组 组装的路由数据
router.addRoutes(routers); // 会有告警
next({...to, replace: true}); // hack方法, 确保 addRoutes 已完成
}).catch(err => {
console.error('Error:' + err);
});
} else {
// 已处理好用户可访问的路由,直接按导航跳转
// 判断是否licence过期
const licenceOverDue = store.getters['licence/getSystemLicenseoverdue']
if (startWith('/home/settings/licence', to.path)) {
next()
} else {
if (licenceOverDue) {
next('/home/settings/licence/current');
} else {
next();
}
}
}
}
} else {
// 未登录或者登录过期,刷新浏览器和进行路由跳转时应切换到登录界面
if (to.path === '/login') {
next();
} else {
store.commit('NEED_PUSH_MSG', {content: 'loginAgainPlz', type: 'warning'});
next('/login');
}
}
})
}
修改之后(vue3):
router.addRoutes(res);
改写成===>
router.addRoute(res);
// 会出现的添加生成路由表的写法(各自千秋)
```javascript
let routers = store.state.permission.routers;
router.addRoutes(routers); // 会有告警
// 根据用户权限生成可访问的路由表,由各自的store生成accessRouter
for (let i = 0; i < accessRouter.length; i += 1) {
const element = accessRouter[i]
router.addRoute(routers); // 会有告警
}
💞💖💓💗每个时代,
✨🌟⭐️💫都悄悄犒赏会学习的人。
更多推荐
已为社区贡献1条内容
所有评论(0)