Vue/Quasar:如何添加持久查询参数

问题描述 投票:0回答:1

给定 Vue 3 和 Quasar 2.6 上的应用程序。
我正在尝试在网址中添加一个参数,以便它在导航过程中保持不变。这个想法是,它在应用程序启动时使用它来初始化应用程序状态,然后保存在 url 中。状态更改时,参数会更新。
我在这里搜索了问题,看起来我应该使用路由器的

beforeEach
钩子。问题是我收到“导航防护中的无限重定向”错误。

路由器/routes.ts:

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: MainLayout,
    props: true,
    children: [
      {
        path: '',
        component: IndexPage,
      },
      {
        path: 'configuration',
        component: ConfigurationPage,
      },
    ],
  },
  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];

export default routes;

路由器/index.ts:

import routes from './routes';

export default route(function (/* { store, ssrContext } */) {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : (process.env.VUE_ROUTER_MODE === 'history' ? createWebHistory : createWebHashHistory);

  const Router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,
    history: createHistory(process.env.VUE_ROUTER_BASE),
  });

  return Router;
});

应用程序.vue:

export default defineComponent({
  name: 'App',
  created: async () => {
    const router = useRouter();

    router.beforeEach((to, from, next) => {
      let toWithQuery = Object.assign({}, to, { query: from.query });
      next(toWithQuery);
    });
  }
});
vue.js vuejs3 vue-router
1个回答
0
投票

当您从导航防护返回除

next()
以外的任何内容时,您将使当前导航无效并导致执行新的导航。任何new导航都需要通过all导航守卫。
next(toWithQuery)
始终触发新的导航,导致
router.beforeEach
始终再次运行,无限重复。

我建议删除

next
参数。不再推荐

当导航有效时,你实际上不需要返回任何东西

如果什么都没有,则返回

undefined
true
,导航生效,并调用下一个导航守卫。

beforeEach 防护的工作版本示例如下:

router.beforeEach((to, from) => {
  if (!Object.keys(to.query).length) {
    return Object.assign({}, to, { query: from.query })
  }
})

仅当当前不存在查询时,此代码才会向

to
路由添加查询。否则,导航将被验证。该守卫最多只能运行两次(一次用于添加查询,一次用于成功验证)

© www.soinside.com 2019 - 2024. All rights reserved.