Vue JS 3 Tutorial for Beginners #8 - The Vue Router

Key Takeaways from the Video

  1. Vue Single Page Applications:

    • Vue.js is used for creating single-page applications (SPAs).
    • Only one HTML document is served initially and Vue.js manages the routing from there on the client side.
    • Vue switches out components for different routes instead of requesting new HTML pages from the server.
  2. Routing in Vue.js:

    • Vue Router is a separate package used in conjunction with Vue.js to enable routing.
    • Routes are defined as an array of route objects, each containing path, name, and the component that should be rendered.
    • The router instance is created at the end of the router/index.js file, defining the mapping of routes to components.
  3. Project Setup:

    • You can set up routing in a Vue project by installing and configuring Vue Router manually or using Vue CLI.
    • Vue CLI can scaffold a project with routing setup by selecting the router feature during project creation.
    • When setting up the router using Vue CLI, you have the option to use history mode for cleaner URLs without hashes.
  4. Router View Tag:

    • router-view is a Vue Router special tag that dynamically injects the appropriate route component based on the current URL.
    • The router-view tag is usually placed in the App.vue file, which is the root component.
    • Surrounding layout components such as headers or footers will remain the same across different routes.
  5. Router Link Tag:

    • Vue uses the <router-link> tag to intercept navigation requests and handles them within the single-page app without refreshing the page.
    • The to attribute of <router-link> can be data-bound to link to dynamic routes.
    • <router-link> automatically applies active classes for styling active links.
  6. Route Parameters and Dynamic Routing:

    • Dynamic segments in a route can be defined using a colon (e.g., /jobs/:id).
    • Route parameters are accessible within components via $route.params.
    • Vue Router allows for route parameters to be passed as props to route components.
  7. 404 Page and Redirects:

    • A catch-all 404 page can be configured using a route that matches all paths that are not defined elsewhere.
    • Redirection can be set up in the Vue Router for cases where an old route should redirect to a new one.
  8. Programmatic Navigation:

    • Inside components, you can programmatically navigate the history of the router using this.$router.go(-1) to go back and this.$router.go(1) to go forward.
    • To redirect, you use this.$router.push({ name: 'Home' }) to push a new route onto the history stack.
  9. Folder Structure:

    • views folder contains route components.
    • components folder holds reusable components.
    • It's possible to group related components in subfolders within views.
    • The structure of the folders should be logical and consistent.

Share these insights with your friends