vue-router4版本第一次打开界面不匹配路由问题怎么解决

其他教程   发布日期:2025年02月13日   浏览次数:217

这篇文章主要介绍“vue-router4版本第一次打开界面不匹配路由问题怎么解决”,在日常操作中,相信很多人在vue-router4版本第一次打开界面不匹配路由问题怎么解决问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”vue-router4版本第一次打开界面不匹配路由问题怎么解决”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

问题:[Vue Router warn]: No match found for location with path “/home”

因为以前是一次性添加路由使用的是addRoutes,现在成了addRoute一个一个添加,我登陆后动态添加路由后,明明已经加了路由,打开却警告不匹配而且一片空白,然后查了说是需要

  1. next({...to,replace:true})

这个…to,表示会再去一次这个路径,才能激活那个路径的匹配
以下是我的登录和加载菜单的逻辑和写法

  1. login() {
  2. this.$refs.ruleForm.validate(valid => {
  3. if (valid) {
  4. this.axios.postForm('/login',this.loginForm).then(response => {
  5. let data = response.data;
  6. this.$store.commit('login', data)
  7. let redirect = this.$route.query.redirect
  8. this.$router.push({path: (redirect === undefined) ? '/home' : redirect});
  9. })
  10. } else {
  11. return false;
  12. }
  13. });
  14. }

登录后会跳转,然后触发全局守卫

  1. router.beforeEach((to, from, next) => {//配置路由守卫
  2. if(to.path==='/'){
  3. next()
  4. }else if(store.state.user.id){
  5. initMenus(router,store,next,to)
  6. }else{
  7. next({ path: '/',query: {redirect: to.path}});
  8. }
  9. });

然后第一次会进入initMenus函数初始化路由

  1. import axios from "axios";
  2. export const initMenus = (router, store,next,to) => {//按F5刷新的话vuex里的会被清空,长度变为0
  3. if (store.state.menu !== null) {
  4. next()
  5. }else {
  6. axios.get("/menu").then(response => {
  7. if (response) {
  8. let responseData = response.data
  9. if (responseData.flag) {
  10. store.state.menu = responseData.data
  11. initRoute(router,store.state)
  12. next({...to,replace:true})//解决router4版本的第一次路由不匹配问题
  13. } else {
  14. this.$ElMessage.error('请求菜单失败')
  15. }
  16. }
  17. })
  18. }
  19. }
  20. const initRoute = (router,state)=> {
  21. const loadView = view => {//这种引入方式控制台不会报警告
  22. // 路由懒加载
  23. return () => import(`@/views/${view}`)
  24. };
  25. const menus = state.menu
  26. const firstLevelMenu = {
  27. children: [],
  28. component: loadView('home/HomeView.vue')
  29. }
  30. menus.forEach(menu=>{
  31. menu.component = loadView(menu.component)
  32. if(menu.children === null || menu.children.length === 0){
  33. firstLevelMenu.children.push(menu)
  34. }else{
  35. menu.children.forEach(children=>{
  36. children.component = loadView(children.component)
  37. })
  38. router.addRoute(menu)
  39. }
  40. })
  41. router.addRoute(firstLevelMenu)
  42. }

一定要在添加完所有路由后写这个next({…to,replace:true}),而且next不能重复调用

最后可以解决界面空白问题,但是警告不会消失

以上就是vue-router4版本第一次打开界面不匹配路由问题怎么解决的详细内容,更多关于vue-router4版本第一次打开界面不匹配路由问题怎么解决的资料请关注九品源码其它相关文章!