【问题标题】:Infinite loop for vue-router's beforeEach methodvue-router 的 beforeEach 方法的无限循环
【发布时间】:2020-09-30 05:27:33
【问题描述】:

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

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】:

    请不要将状态存储在 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) 等于名称,则它尚未编码,您可以继续对其进行编码。

    【讨论】:

    • 经过几次测试后,我将此标记为已接受的答案,但现在我发现了一个问题。如果to.param.name 是一个无论是解码还是编码都始终保持不变的字符串,它会再次进入无限循环。例如'xyz' === decodeURIComponent('xyz') === encodeURIComponent('xyz').
    • 我现在找到了一种愚蠢的解决方案 :) 在编码 to.param.name 时,我在它的末尾添加了 %20(就像这个 ${encodeURIComponent(to.params.name)}%20)。这样,当它被解码时,它总是不同的
    猜你喜欢
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 2020-07-24
    • 2021-10-05
    相关资源
    最近更新 更多