用 vue 做了一个保存页面历史记录的功能,测试环境 npm run dev好使,npm run build到生产环境就不生效了

    router.afterEach((to) => {
      if (typeof window !== "undefined") {
        localStorage.setItem('to.path', to.fullPath);
      }
    });
    router.beforeEach((to, from, next) => {
      if (typeof window !== "undefined") {
        const topath = localStorage.getItem('to.path');
        if (to.fullPath === '/' && from.fullPath === '/' && topath) {
          router.push(topath);
        }
      }
      next();
    });

报错:Hydration completed but contains mismatches

并且页面显示内容错乱:标题是第二页,内容是首页。

猜测到是因为router.push重新跳转的问题,但不知道怎么修改,最后测试改成下面这样好使。

    router.afterEach((to, from) => {
      if (typeof window !== "undefined") {
        const topath = localStorage.getItem('to.path');
        if (to.fullPath === '/' && from.fullPath === '/' && topath && topath !== '/') {
          router.push({path: topath});
        } else {
          localStorage.setItem('to.path', to.fullPath);
        }
      }
    });

topath !== '/' 是为了避免死循环。问题解决。

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐