Vue 中的动态根 url 结构与 vue-router、route guard 和 Vuex



我有一个看起来像这样的vue路由器:

const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
children: [
{
{
path: 'main',
name: 'main',
component: () => import(/* webpackChunkName: "main" */ './views/main/Main.vue'),
children: [
{
path: 'dashboard',
name: 'main-dashboard',
component: () => import(/* webpackChunkName: "main-dashboard" */ './views/main/Dashboard.vue'),
},
...

有路由防护,因此一旦用户登录,他们就会被定向到/BASE_URL/main/dashboard

public beforeRouteEnter(to, from, next) {
routeGuardMain(to, from, next);
}
public beforeRouteUpdate(to, from, next) {
routeGuardMain(to, from, next);
}
const routeGuardMain = async (to, from, next) => {
if (to.name === 'main') {
next({ name: 'main-dashboard'});
} else {
next();
}
};

我正在以 Vuex 状态存储user_idaccount_id,我希望能够创建一个 url 结构,如下所示:

BASE_URL/<account_id>/dashboard

但是我在从商店访问account_id时遇到问题(我已经设置了getters以获取相关的参数(并在路由保护中的重定向期间将其作为参数传递(其null/未定义,所以我认为我需要在某个地方等待??

我可以为没有路由保护的路径设置动态 url,但不确定如何使用它们。

我已经通读了 vue-router 文档,但无法解决。

请谁能建议我如何实现目标网址结构?抱歉,我的前端技能不足,我是 Vue 的新手.js

谢谢!

找到类似于此链接的解决方案:

定义 Vue-Router 路由时访问 Vuex 状态

const startRouteGuard = async (to, from, next) => {
await dispatchCheckLoggedIn(store);
if (readIsLoggedIn(store)) {
if (to.path === '/login' || to.path === '/') {
if (store.getters.userMembership.account_id === null) {
const watcher = store.watch(store.getters.userMembership.account_id, account_id => {
watcher(); // stop watching
next({ name: 'main', params: { account_id: account_id}});
});
} else {
const account_id = store.getters.userMembership.account_id;
next({ name: 'main', params: { account_id: account_id}});
}
} else {
next();
}
} else if (readIsLoggedIn(store) === false) {
if (to.path === '/' || (to.name as string).startsWith('main')) {
next({name: 'login'});
} else {
next();
}
}
};

最新更新