Installing and Wiring Vue Router: Core Concepts
Router, app, and outlets
Vue Router connects URL locations to Vue components. A route record describes which view matches a path, the router tracks the current location, and router-view renders the component selected by that match. Router-link renders a real anchor with client-side navigation behavior, so it preserves link semantics while avoiding a full document reload for internal routes. These pieces have separate jobs: records define the map, links let a person move through it, and outlets place matched views in the component tree.
Create the router with a history implementation and the route records, install it on the Vue application, then mount the app. Installation must happen before mount so the root component and its descendants can access the router and render route content. The root template normally contains a router-view. A navigation element can contain router-link entries for common destinations.
Choose a history mode deliberately
createWebHistory produces clean paths such as /projects/42. It uses the browser History API and is the usual choice for a production single-page app. The web server must return the application entry document for client-side routes that are not actual static files. Without this fallback, visiting a nested path directly or refreshing it can return a server 404 even though navigating there from the app worked. Configure the fallback narrowly so real asset and API 404 responses are not rewritten to HTML.
createWebHashHistory puts the route after a hash, such as /#/projects/42. The fragment is not sent to the web server, so basic static hosting does not need a path fallback. The trade-off is a different URL shape and less conventional sharing. Pick the mode based on hosting behavior, URL requirements, and deployment constraints rather than treating either mode as universally correct. When deploying under a subpath, configure the router base consistently with the asset base and server mount path.
Installation order and ownership
The router instance should be created once for the application and registered with app.use(router) before app.mount. A child component should normally obtain navigation through router-link, useRouter, or useRoute rather than importing and creating a second router. Multiple instances can disagree about the current location and make tests or navigation difficult to reason about. Keep route definitions near the application routing boundary and split them into modules only when that improves ownership or lazy loading.
Router-link gives an internal destination an accessible anchor contract. It supports keyboard activation, open-in-new-tab behavior, copying the URL, and a destination that can be inspected before navigation. Do not replace every link with a button merely to call router.push. A button is appropriate for an action; a link is appropriate for navigation. Active link classes can style the current destination, but the selected state should remain understandable without color alone.
Root and nested views
The root router-view renders the matched top-level component. A route component may itself contain another router-view when child records define a nested section. This allows a layout such as a project shell to remain mounted while its overview, settings, or members panel changes. Nested routes should reflect a real parent-child relationship in the information architecture; nesting only to shorten route configuration creates needless coupling.
The router does not replace application state management or authorization. It decides which view corresponds to a URL and provides navigation hooks. The component still loads data, handles loading and error states, and checks whether it can present the data. Server endpoints must enforce access independently of route guards. Keeping these boundaries clear prevents the URL map from becoming a hidden store or security system.
For a first setup, wire one route, one router-link, and one outlet, then verify both in-app navigation and a direct refresh on the route. That test crosses the important boundaries: app installation, route matching, client rendering, and server fallback. Add nested routes, guards, and lazy imports only when the application needs them.
Installing and Wiring Vue Router: Practice
Create a small route table
The following setup shows the ownership boundary in one place. HomeView and ProjectListView stand for ordinary Vue components. createRouter receives route records and a history implementation, then the app installs the router before mounting. The root component supplies the outlet where the current route view appears.
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import HomeView from './views/HomeView.vue'
import ProjectListView from './views/ProjectListView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{ path: '/', name: 'home', component: HomeView },
{ path: '/projects', name: 'projects', component: ProjectListView },
],
})
createApp(App).use(router).mount('#app')
The root template can render navigation with router-link and one router-view. Use an actual anchor for external destinations and router-link for internal routes. If an internal destination is generated dynamically, use a named route when possible so a path change does not require updating strings across many components. Avoid placing route construction logic in a shared button component; the destination belongs to the feature or navigation layer.
Verify hosting as well as client navigation
Start the app and click between both routes. Then paste each URL into a fresh browser tab and refresh it. The first test exercises router-link and client-side matching; the second asks the server to serve the nested URL directly. If direct loading fails with a server 404, fix the host fallback or deployment base rather than adding a client-side workaround that only hides the symptom.
Use a minimal fallback that sends known application paths to the entry document while preserving 404s for missing JavaScript, images, and API endpoints. A blanket rewrite can turn a missing script into an HTML response, producing confusing MIME-type errors. Test the production build on the same kind of host used for deployment because a development server usually supplies history fallback automatically.
If the app is hosted at a URL prefix, confirm that three values agree: the document base, the router history base, and the server's mounted path. A mismatch can create links that work locally but point outside the application in production. Test a deep route after deployment and inspect generated asset URLs. For hash history, direct deep links avoid server fallback, but the hash itself remains part of the address and should be acceptable to the product.
Exercise the routing boundary
Add a not-found route and a navigation link to it. Verify that the root outlet renders the expected view and that active navigation updates. Temporarily omit app.use(router) and observe the missing injection or outlet behavior; restore it before adding feature code. Then move the application under a subpath and verify that the router base and asset URLs still resolve. These experiments isolate setup mistakes from component mistakes.
Use browser history controls after navigating several times. Back and forward should restore the URL and matched view without creating duplicate entries for every internal state update. Use replace navigation for corrections such as canonicalizing an invalid path; use push for a user-visible step that should be traversable with Back. Router setup makes history behavior available, but feature code should choose push or replace intentionally.
For a maintainable application, keep the router instance in the bootstrap layer and export route definitions when they need separate tests or ownership. Do not instantiate it in a component's setup function. A route table should be inspectable without mounting the UI, and a component should be renderable in isolation when its routing dependency is mocked or provided by a test harness. This keeps application wiring explicit and makes failures easier to localize.
Installing and Wiring Vue Router: Trade-offs and Interviews
Deployment determines part of routing
Web history creates conventional URLs but makes the server part of the routing contract. Every valid client-side path must return the app entry document, while missing assets and APIs must still return meaningful errors. Hash history reduces server configuration because the fragment is not sent over HTTP, but it changes URL appearance and may not fit product expectations. Choose with the deployment platform in view and verify the built site rather than relying on a development server.
A base path is another deployment constraint. A site mounted at /portal cannot assume that / is its application root. Configure generated assets, router history, and hosting rewrites consistently. Environment-specific base values should come from the build and deployment configuration, not from hard-coded path concatenation in individual components. Test a deep link, refresh, and static asset request under the deployed prefix.
Keep navigation semantic
Navigation is not a generic click action. router-link preserves anchor behavior, including keyboard activation, link context menus, and opening in a new tab. Use buttons for mutations and local actions. A route link can expose active state, but add an accessible cue and do not rely solely on a color difference. For external sites, use a normal anchor and apply the appropriate security attributes when opening a new browsing context.
Route guards can improve flow, but they are not authorization. A guard can redirect an unauthenticated user before a protected component appears, yet the API must independently reject unauthorized requests. Data can be requested outside the UI and the client can be modified. Treat navigation policy as presentation and server policy as access control.
Testing and troubleshooting
Test route table behavior separately from full browser deployment. A router unit or component test can verify matching and rendered views. A production smoke test should directly request a nested path, refresh, load assets, and verify the fallback does not capture API errors. Back and forward navigation deserve a browser test when history behavior is central to a workflow.
When the outlet is blank, verify the app installed the same router instance that owns the route table, the matched route has a valid component, and the root template contains an outlet. When clicking a link reloads the document, check whether it is an ordinary anchor, an external URL, or a form submission. When refresh fails but client navigation succeeds, inspect server fallback and base-path configuration before editing the route component.
In an interview, explain the route table, history strategy, installation order, and outlet. Then describe the hosting fallback requirement for clean URLs and distinguish client navigation guards from server authorization. A practical answer includes a deep-link refresh test, not just a successful click inside the development server. That demonstrates understanding of both Vue's client router and the HTTP environment it depends on. Also include how the deployed base path affects generated links and asset requests, since local root hosting can conceal configuration errors. Check that CDN and reverse-proxy rewrite rules match the origin behavior, because deployment layers can treat deep paths differently.
Quiz
1. Which statement about Installing and Wiring Vue Router is accurate?
2. When reviewing Installing and Wiring Vue Router, which point must hold?
3. What must a server do to support direct refreshes with web history?
4. When should app.use(router) run?
Flashcards
Question
What is Installing and Wiring Vue Router?
Click to reveal answer
Answer
Register the router plugin and place the view and link outlets.
Question
Installing and Wiring Vue Router: why it matters
Click to reveal answer
Answer
createRouter with history mode decides whether URLs use clean paths or a hash fragment.
Question
Installing and Wiring Vue Router: key detail
Click to reveal answer
Answer
The router-view outlet renders the component matched by the current URL.
Question
Installing and Wiring Vue Router: practical note
Click to reveal answer
Answer
The router-link component generates anchor tags that navigate without full page reloads.
Question
What does web history require from production hosting?
Click to reveal answer
Answer
A fallback for valid client routes that preserves asset and API errors.
Revision Notes
Key Takeaways
- 1. createRouter with history mode decides whether URLs use clean paths or a hash fragment.
- 2. The router-view outlet renders the component matched by the current URL.
- 3. The router-link component generates anchor tags that navigate without full page reloads.
Interview Tips
- • Explain Installing and Wiring Vue Router with one concrete example from real vue work, not a textbook restatement.
- • Discuss the trade-off: when Installing and Wiring Vue Router helps and when a lighter approach wins.
- • Place Installing and Wiring Vue Router inside the Routing with Vue Router phase — interviewers check that you see the progression, not isolated facts.
Cheat Sheet
Installing and Wiring Vue Router Cheat Sheet
Phase: Routing with Vue Router | Level: beginner
Key points:
- createRouter with history mode decides whether URLs use clean paths or a hash fragment.
- The router-view outlet renders the component matched by the current URL.
- The router-link component generates anchor tags that navigate without full page reloads.
- The router must be installed on the app with use before the app is mounted.
Tags: vue, router, setup