Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Vue Router 2.x for Single Page Applications

Tech 2

Essential Concepts of Vue Router

Vue Router is the official routing middleware for Vue.js. It facilitates the creation of Single Page Applications (SPAs) by mapping URL paths to specific components, enabling seamless view transitions without full page reloads.

Core Installation and Setup

For Vue 2 projects, the router is typically installed using version 3 of the package:

npm install vue-router@3 --save

Creating the Router Module

Organize the routing logic in a dedicated file, typically src/router/index.js:

import Vue from 'vue';
import Router from 'vue-router';

// Register the plugin with Vue
Vue.use(Router);

// Initialize the router instance
const routerInstance = new Router({
  routes: []
});

export default routerInstance;

Application Entry Integration

In the main.js file, the router instance must be injected into the root Vue instance to make it available throughout the application:

import Vue from 'vue';
import App from './App.vue';
import router from './router';

new Vue({
  router,
  render: root => root(App)
}).$mount('#app');

Routing Components and Templates

Vue Router provides two built-in components for navigation and display:

  1. <router-link>: Renders an anchor tag for navigation. The to attribute defines the destination path.
  2. <router-view>: Acts as a functional placeholder where the matched component will be rendered.
<template>
  <div id="app-layout">
    <nav>
      <router-link to="/dashboard">Dashboard</router-link>
      <router-link to="/inventory">Inventory</router-link>
      <router-link to="/profile">User Profile</router-link>
    </nav>
    <main>
      <router-view></router-view>
    </main>
  </div>
</template>

Mapping Routes and Redirection

Routes are defined as an array of objects within the router constructor. Redirection allows mapping an initial path to a specific default route.

const routerInstance = new Router({
  routes: [
    { path: '/', redirect: '/dashboard' },
    { path: '/dashboard', component: () => import('@/views/Dashboard.vue') },
    { path: '/inventory', component: () => import('@/views/Inventory.vue') }
  ]
});

Implementing Nested Routes

Hierarchical views can be managed using the children property. This allows components to have their own internal <router-view>.

const routerInstance = new Router({
  routes: [
    {
      path: '/profile',
      component: ProfileParent,
      children: [
        // Default child route
        { path: '', component: GeneralSettings },
        // Named child route
        { path: 'security', component: SecuritySettings }
      ]
    }
  ]
});

Dynamic Route Matching and Props

Paths can contain dynamic segments identified by a colon. Using props: true allows the component to receive these segments as standard props rather than accessing the route object directly.

// Route Definition
{ path: '/product/:sku', component: ProductDetail, props: true }

// ProductDetail.vue
export default {
  props: ['sku'],
  created() {
    console.log('Fetching data for SKU:', this.sku);
  }
}

Alternatively, parameters can be accessed via this.$route.params.sku inside the component template.

Programmatic Navigation

Beyond declarative links, navigation can be controlled via JavaScript using the $router instance methods:

  • this.$router.push('/path'): Navigates to a new URL, adding an entry to the history stack.
  • this.$router.replace('/path'): Navigates without adding a history entry.
  • this.$router.go(n): Moves backward or forward in history by n steps.
methods: {
  handleLogin() {
    // Logic after successful login
    this.$router.push('/dashboard');
  },
  goBack() {
    this.$router.back();
  }
}

Global Navigation Guards

Navigation guards are used to intercept transitions for authorization or logging. The beforeEach guard is executed for every route change.

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('user_session');

  if (to.path === '/admin') {
    if (isAuthenticated) {
      next(); // Proceed to route
    } else {
      next('/login'); // Redirect to login
    }
  } else {
    next(); // Always call next()
  }
});

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.