简体   繁体   中英

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. 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. I tried using the beforeunload event like this

<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". 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.

Then you can prevent the default behaviour, modify the DOM however you like, and then manipulate the URL using the History API .

You also need to handle popState events so that the back button continues to work.


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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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