Vue3动态路由
1、引入router :
import {useRouter} from 'vue-router'
2、定义
let router = useRouter();
3、动态添加路由
router.addRoute({name:"users", path: '/User/users', component: ()=>import("/src/views/User/Users.vue") });
4、跳转要用push,直接通过浏览器地址打不开
router.push("/User/Users")
5、解决刷新空白,找不到路由
a、将通过后台获取的动态路由添加到缓存
window.localStorage.router = (JSON.stringify(getRouter)); //getRouter是通过后台获取到的动态路由对象
b、在导航守卫里面里面添加动态路由
import {reactive, ref } from 'vue'
let registerRouteFresh = ref(true) // 定义标识,记录路由是否添加 let getRouter = JSON.parse(window.localStorage.router ? window.localStorage.router : null); //取出路由 router.beforeEach((to, from, next) => { if (registerRouteFresh.value && getRouter.length > 0) { for(let item of getRouter){ router.addRoute(item); } registerRouteFresh.value = false next({ path: `${to.path}` }); } else{ next(); } });