Single Page Application Routing Single Page Application Routing vue.js vue.js

Single Page Application Routing


In Vue Router (and I assume other libraries/frameworks are the same) this is achieved through the HTML5 history API (pushState(), replaceState(), and popstate) which allows you to manipulate the browser's history but won't cause the browser to reload the page or look for a resource, keeping the UI in sync with the URL.

For example, observe what happens to the address bar when you enter this command in your browser's console

history.pushState({urlPath:'/some/page/on/stackoverflow'},"",'/some/page/on/stackoverflow')

The new URL is even added to your browser's history so if you navigate away from the page and come back to it you'll be directed to the new URL.

Of course all these URLs are non-existent on the server. So to avoid the problem of 404 errors when a user tries to directly access a non-existent resource you'd have to add a fallback route that redirects to your index.html page where your app lives.

Vue Router's HTML5 History Mode

React Router's <BrowserRouter>


How does the browser know when to ask the server for a resource andwhen to ask the single page application for a spa-page controlled by arouter?

SPA Frameworks use routing libraries.

Suppose your javascript app is already loaded in the browser. When you navigate to a route that is defined in your routes array, the library prevents an http call to the server and handles it internally in your javascript code. Otherwise the call is forwarded to the server as a GET Http request.

here is an answer that discribes this behaviour with a clear scenario