原生history库 createBrowser方法中的history.push会导致file not found

我在学习过程中引用原生history库到我的html文件里面,然后在使用的时候createHashHistory()方法创建的history对象是完全没问题的,但是createBrowserHistory()创建的对象进行push的时候,地址栏被清空了,就剩下一个我最后push进去的地址/test,导致file not found报错.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>History</title>
  </head>
  <body>  
 <button onclick="window.push('/test')">click me to push test </button>
    <script type="module">
      import { createBrowserHistory } from "https://unpkg.com/history/history.production.min.js"
      let history = createBrowserHistory()

      window.push = function push(path) {
        history.push(path)
        return false
      }

      history.listen(({ action, location }) => {
          console.log( `The current URL is ${location.pathname}${location.search}${location.hash}`);
          console.log(`The last navigation action was ${action}`); 
      });
    </script>
</body>
</html>

跪求路过的大佬给答疑.肥肠感谢.肥肠肥肠感谢~~~

阅读 2.6k
1 个回答

你是不是在资源管理器/访达里直接双击打开文件、以 file 形式浏览的网页?

你需要放到一个 WebServer 下、以 http 的形式访问才可以使用 history。

如果用的是 VSCode 作为 IDE 的话可以装个 LiveServer 插件,本地启动一个 WebServer。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题