vue-router的beforeEach方法的无限循环

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

如果params的名称是特定名称,并且我不知道为什么这不起作用,我想替换toto之一。

export const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior() {
    return { x: 0, y: 0 };
  },
  routes: [
    {
      name: 'Details Page',
      path: 'details/:name/:id',
      component: () => import('@/views/Details.vue'),
      meta: {
        encode: true,
      },
    },
    // other routes... (none of them has encode = true)
  ]
});

function needsEncode(route) {
  return route.meta && route.meta.encode;
}

router.beforeEach(async (to, from, next) => {
  if (to.name === 'Details Page' && needsEncode(to)) {
    const toEncoded = Object.assign({}, to, {
      meta: {
        encode: false,
      },
      params: {
        name: encodeURIComponent(to.params.name),
        id: to.params.id,
     },
    });
    return next(toEncoded);
  }
  return next();
}

我在做什么错?

vue.js vue-router infinite-loop
1个回答
0
投票

请不要将状态存储在meta属性中。相反,您可以检查名称是否已编码:

  • 首先:将代码移至页面组件。
function needsEncode(route) {
  return route.meta && route.meta.encode && ( // <-- changes start here
    decodeURIComponent(to.params.name) === to.params.name
  ) // <-- changes ends here
}
router.beforeEach(async (to, from, next) => {
  if (to.name === 'Details Page' && needsEncode(to)) {
    const toEncoded = Object.assign({}, to, {
      // remove meta
      //meta: {
      //  encode: false,
      //},
      params: {
        name: encodeURIComponent(to.params.name),
        id: to.params.id,
     },
    });
    return next(toEncoded);
  }
  return next();
}

如果decodeURIComponent(to.params.name)等于名称,则尚未对其进行编码,您可以继续对其进行编码。

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