简体   繁体   English

如何在普通 javascript 中实现基本的类似角度的路由

[英]How to implement basic angular-like routing in plain javascript

I want to write a simple javascript implementation of Angular-like routing, but I can't figure out how to do it.我想写一个简单的 javascript 实现类似 Angular 的路由,但我不知道该怎么做。 Let's say I have an Index page and I'd like to navigate to Index/2 by a means of <a href="Index/2">Navigate Like in Angular</a> , yet prevent the request being sent to the server and instead get some event which I can handle.假设我有一个 Index 页面,我想通过<a href="Index/2">Navigate Like in Angular</a>导航到 Index/2 ,但阻止将请求发送到服务器而是得到一些我可以处理的事件。 I tried using the beforeunload event like this我尝试使用这样的 beforeunload 事件

<script>
        window.onbeforeunload = function (ev) {
 
            ev.preventDefault();
            return '';
        };
 
    </script>

but this approach doesn't work.但这种方法行不通。 First, it displays a popup message which I'm not interested in, and second, if I press cancel, the url in the browser address control is still "http://.../Index" and I don't know a way to "silently" modify it to "http://.../Index/2".首先,它显示一条我不感兴趣的弹出消息,其次,如果我按下取消,浏览器地址控件中的 url 仍然是“http://.../Index”,我不知道“静默”的方式将其修改为“http://.../Index/2”。 Any help will be most appreciated.任何帮助将不胜感激。

You can't intercept the browser leaving the page to achieve this.您无法拦截离开页面的浏览器来实现此目的。

You need to have a click event listener that captures the link being activated instead.您需要有一个click事件侦听器来捕获被激活的链接。

Then you can prevent the default behaviour, modify the DOM however you like, and then manipulate the URL using the History API .然后您可以阻止默认行为,根据需要修改 DOM,然后使用History API 操作 URL

You also need to handle popState events so that the back button continues to work.您还需要处理popState 事件,以便后退按钮继续工作。


Keep in mind that you do need to have the server deliver something useful when the browser asks for that new URL as an entry point to your SPA and that that is best provided by having a server-side rendered version of your application.请记住,当浏览器要求新的 URL 作为 SPA 的入口点时,您确实需要让服务器提供一些有用的东西,并且最好通过拥有应用程序的服务器端呈现版本来提供。

A hackier approach is to just deliver some skeleton HTML and bootstrap everything with client-side JS … but then you run into problems with determining when the server should report a 404 error.一个更老套的方法是只提供一些框架 HTML 并使用客户端 JS 引导所有内容……但是在确定服务器何时应该报告 404 错误时遇到问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM