CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vue-router

Official router for Vue.js 2 providing declarative routing, navigation guards, and nested route configuration.

Pending
Overview
Eval results
Files

route-configuration.mddocs/

Route Configuration

Route definition system supporting nested routes, dynamic parameters, route-level guards, and comprehensive configuration options for building complex routing structures.

Capabilities

Route Definition

Define routes with components, parameters, and metadata.

/**
 * Route configuration object defining a single route
 */
interface RouteConfig {
  /** The path pattern for this route */
  path: string;
  /** Component to render for this route */
  component?: Component;
  /** Unique name for this route (enables named routing) */
  name?: string;
  /** Child routes for nested routing */
  children?: RouteConfig[];
  /** Redirect target when this route is matched */
  redirect?: RedirectOption;
  /** Alternative path(es) that should match this route */
  alias?: string | string[];
  /** Custom metadata attached to this route */
  meta?: RouteMeta;
  /** Route-level navigation guard */
  beforeEnter?: NavigationGuard;
  /** Whether path matching should be case sensitive */
  caseSensitive?: boolean;
  /** Options for path-to-regexp matching */
  pathToRegexpOptions?: PathToRegexpOptions;
}

/**
 * Multi-view route configuration with named components
 */
interface RouteConfigMultipleViews {
  path: string;
  /** Named components for multiple router-view outlets */
  components?: Dictionary<Component>;
  /** Props configuration for each named component */
  props?: Dictionary<boolean | Object | RoutePropsFunction>;
  name?: string;
  children?: RouteConfig[];
  redirect?: RedirectOption;
  alias?: string | string[];
  meta?: RouteMeta;
  beforeEnter?: NavigationGuard;
  caseSensitive?: boolean;
  pathToRegexpOptions?: PathToRegexpOptions;
}

type RedirectOption = RawLocation | ((to: Route) => RawLocation);
type RoutePropsFunction = (route: Route) => Object;

Usage Examples:

// Basic route configuration
const routes = [
  // Static route
  { path: '/', component: Home },
  
  // Route with parameters
  { path: '/user/:id', component: User, name: 'user' },
  
  // Route with query and hash support
  { path: '/search', component: Search },
  
  // Route with redirect
  { path: '/home', redirect: '/' },
  
  // Route with alias
  { path: '/users', component: Users, alias: '/people' },
  
  // Route with metadata
  { 
    path: '/admin', 
    component: Admin, 
    meta: { requiresAuth: true, role: 'admin' }
  }
];

Nested Routes

Configure hierarchical route structures with parent and child relationships.

/**
 * Nested route configuration with parent-child relationships
 */
interface NestedRouteConfig extends RouteConfig {
  children?: RouteConfig[];
}

Usage Examples:

const routes = [
  {
    path: '/user/:id',
    component: User,
    children: [
      // Empty path means /user/:id
      { path: '', component: UserHome },
      
      // /user/:id/profile
      { path: 'profile', component: UserProfile },
      
      // /user/:id/posts  
      { path: 'posts', component: UserPosts },
      
      // Nested parameters: /user/:id/post/:postId
      { path: 'post/:postId', component: UserPost }
    ]
  }
];

Dynamic Route Matching

Configure routes with dynamic segments, optional parameters, and pattern matching.

/**
 * Path-to-RegExp options for advanced pattern matching
 */
interface PathToRegexpOptions {
  /** Case sensitive matching */
  sensitive?: boolean;
  /** Strict mode (disallow optional trailing delimiter) */
  strict?: boolean;
  /** End matching (pattern should end at end of string) */
  end?: boolean;
}

Usage Examples:

const routes = [
  // Required parameter
  { path: '/user/:id', component: User },
  
  // Optional parameter
  { path: '/user/:id?', component: User },
  
  // Wildcard (catch-all)
  { path: '/product/*', component: Product },
  
  // Multiple parameters
  { path: '/user/:id/post/:postId', component: Post },
  
  // Parameter with regex pattern
  { path: '/user/:id(\\d+)', component: User }, // Only numeric IDs
  
  // Advanced path-to-regexp options
  {
    path: '/case-sensitive',
    component: Component,
    pathToRegexpOptions: { sensitive: true }
  }
];

Route Props

Configure how route parameters are passed to components as props.

/**
 * Props configuration for passing route data to components
 */
interface RouteProps {
  /** Boolean mode: pass all params as props */
  props?: boolean;
  /** Object mode: static props object */
  props?: Object;
  /** Function mode: dynamic props based on route */
  props?: RoutePropsFunction;
  /** Named views: props config for each named component */
  props?: Dictionary<boolean | Object | RoutePropsFunction>;
}

type RoutePropsFunction = (route: Route) => Object;

Usage Examples:

const routes = [
  // Boolean mode - pass all route.params as props
  { path: '/user/:id', component: User, props: true },
  
  // Object mode - static props
  { 
    path: '/hello', 
    component: Hello, 
    props: { greeting: 'Hello World!' }
  },
  
  // Function mode - dynamic props
  { 
    path: '/search', 
    component: Search, 
    props: (route) => ({ 
      query: route.query.q,
      page: parseInt(route.query.page) || 1
    })
  },
  
  // Named views with different props
  {
    path: '/dashboard',
    components: {
      default: Dashboard,
      sidebar: Sidebar
    },
    props: {
      default: true,
      sidebar: { collapsed: false }
    }
  }
];

Route Metadata

Attach custom data to routes for use in navigation guards and components.

/**
 * Custom metadata object attached to routes
 */
interface RouteMeta extends Record<string | number | symbol, any> {}

Usage Examples:

const routes = [
  {
    path: '/admin',
    component: Admin,
    meta: { 
      requiresAuth: true,
      roles: ['admin', 'moderator'],
      title: 'Admin Panel',
      breadcrumb: 'Administration'
    }
  },
  {
    path: '/public',
    component: Public,
    meta: {
      public: true,
      analytics: { category: 'public-pages' }
    }
  }
];

// Access in components
export default {
  created() {
    console.log(this.$route.meta.title); // 'Admin Panel'
  }
};

// Access in navigation guards
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    next('/login');
  } else {
    next();
  }
});

Route-level Guards

Configure navigation guards that apply to specific routes.

/**
 * Route-level navigation guard
 * @param to - Target route being navigated to
 * @param from - Current route being navigated away from  
 * @param next - Function to call to continue navigation
 */
type NavigationGuard = (to: Route, from: Route, next: NavigationGuardNext) => any;

interface RouteGuardConfig {
  beforeEnter?: NavigationGuard;
}

Usage Examples:

const routes = [
  {
    path: '/admin',
    component: Admin,
    beforeEnter: (to, from, next) => {
      // Check authentication
      if (isAuthenticated() && hasAdminRole()) {
        next(); // Allow access
      } else {
        next('/login'); // Redirect to login
      }
    }
  },
  {
    path: '/user/:id',
    component: UserProfile,
    beforeEnter: async (to, from, next) => {
      try {
        // Validate user exists
        await validateUser(to.params.id);
        next();
      } catch (error) {
        next('/not-found');
      }
    }
  }
];

Router Configuration

Configure router-wide options and behavior.

/**
 * Router constructor options
 */
interface RouterOptions {
  /** Array of route configurations */
  routes?: RouteConfig[];
  /** Routing mode */
  mode?: 'hash' | 'history' | 'abstract';
  /** Base URL for all routes */
  base?: string;
  /** Whether to fallback to hash mode when history is not supported */
  fallback?: boolean;
  /** Default active class for RouterLink */
  linkActiveClass?: string;
  /** Default exact active class for RouterLink */
  linkExactActiveClass?: string;
  /** Custom query string parser */
  parseQuery?: (query: string) => Object;
  /** Custom query string serializer */
  stringifyQuery?: (query: Object) => string;
  /** Scroll behavior handler */
  scrollBehavior?: (to: Route, from: Route, savedPosition?: Position) => PositionResult;
}

Usage Examples:

const router = new VueRouter({
  mode: 'history',
  base: '/my-app/',
  routes,
  
  // Custom link classes
  linkActiveClass: 'is-active',
  linkExactActiveClass: 'is-exact-active',
  
  // Custom query handling
  parseQuery(query) {
    // Custom parsing logic
    return customQueryParser(query);
  },
  
  stringifyQuery(obj) {
    // Custom serialization logic  
    return customQuerySerializer(obj);
  },
  
  // Scroll behavior
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    }
    if (to.hash) {
      return { selector: to.hash };
    }
    return { x: 0, y: 0 };
  }
});

Types

interface RouteRecord {
  path: string;
  regex: RegExp;
  components: Dictionary<Component>;
  instances: Dictionary<Vue>;
  name?: string;
  parent?: RouteRecord;
  redirect?: RedirectOption;
  matchAs?: string;
  meta: RouteMeta;
  beforeEnter?: NavigationGuard;
  props: boolean | Object | RoutePropsFunction | Dictionary<boolean | Object | RoutePropsFunction>;
}

type Component = {} | Vue.Component | Vue.AsyncComponent;
type Dictionary<T> = { [key: string]: T };

interface Position {
  x: number;
  y: number;
}

type PositionResult = Position | { 
  selector: string; 
  offset?: Position;
  behavior?: ScrollBehavior;
} | void;

Install with Tessl CLI

npx tessl i tessl/npm-vue-router

docs

components.md

composables.md

index.md

navigation-guards.md

route-configuration.md

router-instance.md

tile.json