问题:[Vue Router warn]: No match found for location with path “/home”
因为以前是一次性添加路由使用的是addRoutes,现在成了addRoute一个一个添加,我登陆后动态添加路由后,明明已经加了路由,打开却警告不匹配而且一片空白,然后查了说是需要
next({...to,replace:true})
这个…to,表示会再去一次这个路径,才能激活那个路径的匹配
以下是我的登录和加载菜单的逻辑和写法
login() {
this.$refs.ruleForm.validate(valid => {
if (valid) {
this.axios.postForm('/login',this.loginForm).then(response => {
let data = response.data;
this.$store.commit('login', data)
let redirect = this.$route.query.redirect
this.$router.push({path: (redirect === undefined) ? '/home' : redirect});
})
} else {
return false;
}
});
}
登录后会跳转,然后触发全局守卫
router.beforeEach((to, from, next) => {//配置路由守卫
if(to.path==='/'){
next()
}else if(store.state.user.id){
initMenus(router,store,next,to)
}else{
next({ path: '/',query: {redirect: to.path}});
}
});
然后第一次会进入initMenus函数初始化路由
import axios from "axios";
export const initMenus = (router, store,next,to) => {//按F5刷新的话vuex里的会被清空,长度变为0
if (store.state.menu !== null) {
next()
}else {
axios.get("/menu").then(response => {
if (response) {
let responseData = response.data
if (responseData.flag) {
store.state.menu = responseData.data
initRoute(router,store.state)
next({...to,replace:true})//解决router4版本的第一次路由不匹配问题
} else {
this.$ElMessage.error('请求菜单失败')
}
}
})
}
}
const initRoute = (router,state)=> {
const loadView = view => {//这种引入方式控制台不会报警告
// 路由懒加载
return () => import(`@/views/${view}`)
};
const menus = state.menu
const firstLevelMenu = {
children: [],
component: loadView('home/HomeView.vue')
}
menus.forEach(menu=>{
menu.component = loadView(menu.component)
if(menu.children === null || menu.children.length === 0){
firstLevelMenu.children.push(menu)
}else{
menu.children.forEach(children=>{
children.component = loadView(children.component)
})
router.addRoute(menu)
}
})
router.addRoute(firstLevelMenu)
}
一定要在添加完所有路由后写这个next({…to,replace:true}),而且next不能重复调用
最后可以解决界面空白问题,但是警告不会消失