Routing
Client-Side vs. Server-Side Routing
Section titled “Client-Side vs. Server-Side Routing”Routing on the server side means the server is sending a response based on the URL path that the user is visiting. When we click on a link in a traditional server-rendered web app, the browser receives an HTML response from the server and reloads the entire page with the new HTML.
In a Single-Page Application (SPA), however, the client-side JavaScript can intercept the navigation, dynamically fetch new data, and update the current page without full page reloads. This typically results in a more snappy user experience, especially for use cases that are more like actual “applications”, where the user is expected to perform many interactions over a long period of time.
In such SPAs, the “routing” is done on the client side, in the browser. A client-side router is responsible for managing the application’s rendered view using browser APIs such as History API or the hashchange
event.
Official Router
Section titled “Official Router”Vue is well-suited for building SPAs. For most SPAs, it’s recommended to use the officially-supported
Simple Routing from Scratch
Section titled “Simple Routing from Scratch”If you only need very simple routing and do not wish to involve a full-featured router library, you can do so with hashchange
events
Here’s a bare-bone example:
<script>import Home from "./Home.vue";import About from "./About.vue";import NotFound from "./NotFound.vue";
const routes = { "/": Home, "/about": About,};
export default { data() { return { currentPath: window.location.hash, }; }, computed: { currentView() { return routes[this.currentPath.slice(1) || "/"] || NotFound; }, }, mounted() { window.addEventListener("hashchange", () => { this.currentPath = window.location.hash; }); },};</script>
<template> <a href="#/">Home</a> | <a href="#/about">About</a> | <a href="#/non-existent-path">Broken Link</a> <component :is="currentView" /></template>