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

router-instance.mddocs/

Router Instance

Core router functionality for navigation, route matching, and configuration management. The VueRouter class is the main entry point for all routing operations.

Capabilities

VueRouter Constructor

Creates a new router instance with the provided configuration.

/**
 * Creates a new router instance
 * @param options - Router configuration options
 */
constructor(options?: RouterOptions);

interface RouterOptions {
  routes?: RouteConfig[];
  mode?: 'hash' | 'history' | 'abstract';
  base?: string;
  fallback?: boolean;
  linkActiveClass?: string;
  linkExactActiveClass?: string;
  parseQuery?: (query: string) => Object;
  stringifyQuery?: (query: Object) => string;
  scrollBehavior?: (to: Route, from: Route, savedPosition?: Position) => PositionResult;
}

Usage Example:

import VueRouter from 'vue-router';

const router = new VueRouter({
  mode: 'history',
  base: '/app/',
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    }
    return { x: 0, y: 0 };
  }
});

Instance Properties

Access current router state and configuration.

/**
 * Current Vue app instance
 */
app: Vue;

/**
 * Original options object passed to create the Router
 */
options: RouterOptions;

/**
 * Configured mode when creating the Router instance
 */
mode: 'hash' | 'history' | 'abstract';

/**
 * Current active Route object
 */
currentRoute: Route;

Static Properties

Access VueRouter class-level utilities and constants.

/**
 * Vue plugin install function
 */
static install: PluginFunction<never>;

/**
 * Vue Router version string
 */
static version: string;

/**
 * Utility function to check if error is navigation failure
 */
static isNavigationFailure: typeof isNavigationFailure;

/**
 * Navigation failure type enum for checking specific failure types
 */
static NavigationFailureType: {
  [k in keyof typeof NavigationFailureType]: NavigationFailureType
};

/**
 * Initial route location object
 */
static START_LOCATION: Route;

Usage Examples:

// Check Vue Router version
console.log(VueRouter.version); // "3.6.5"

// Check for navigation failures
router.push('/some-route').catch(error => {
  if (VueRouter.isNavigationFailure(error, VueRouter.NavigationFailureType.aborted)) {
    console.log('Navigation was aborted');
  }
});

// Access initial route
console.log(VueRouter.START_LOCATION); // Initial route object

// Plugin installation (done automatically with Vue.use())
Vue.use(VueRouter); // Calls VueRouter.install internally

Programmatic Navigation

Navigate programmatically using router methods.

/**
 * Navigate to a new URL by pushing an entry in the history stack
 * @param location - Route location to navigate to
 * @returns Promise that resolves to the destination route
 */
push(location: RawLocation): Promise<Route>;

/**
 * Navigate with callback functions (legacy)
 * @param location - Route location to navigate to
 * @param onComplete - Success callback
 * @param onAbort - Error/abort callback
 */
push(location: RawLocation, onComplete?: (route: Route) => void, onAbort?: ErrorHandler): void;

/**
 * Navigate by replacing the current entry in the history stack
 * @param location - Route location to navigate to
 * @returns Promise that resolves to the destination route
 */
replace(location: RawLocation): Promise<Route>;

/**
 * Navigate with callback functions (legacy)
 * @param location - Route location to navigate to  
 * @param onComplete - Success callback
 * @param onAbort - Error/abort callback
 */
replace(location: RawLocation, onComplete?: (route: Route) => void, onAbort?: ErrorHandler): void;

/**
 * Move forward or backward through the history
 * @param n - Number of steps to move (positive = forward, negative = backward)
 */
go(n: number): void;

/**
 * Go back one step in history
 */
back(): void;

/**
 * Go forward one step in history  
 */
forward(): void;

Usage Examples:

// Navigate to a new route
router.push('/users/123');
router.push({ name: 'user', params: { id: '123' }});
router.push({ path: '/users/123', query: { tab: 'profile' }});

// Replace current route
router.replace('/login');

// History navigation
router.go(-1); // Go back one page
router.back(); // Same as go(-1)
router.forward(); // Same as go(1)

// Using promises
router.push('/users').then(route => {
  console.log('Navigation completed', route);
}).catch(error => {
  console.log('Navigation failed', error);
});

Route Resolution and Matching

Resolve and match routes programmatically.

/**
 * Resolve a route location to a route object
 * @param to - Route location to resolve
 * @param current - Current route (defaults to currentRoute)
 * @param append - Whether to append to current path
 * @returns Resolved route information
 */
resolve(to: RawLocation, current?: Route, append?: boolean): {
  location: Location;
  route: Route;
  href: string;
  normalizedTo: Location;
  resolved: Route;
};

/**
 * Match a raw location against current routes
 * @param raw - Raw location to match
 * @param current - Current route context
 * @param redirectedFrom - Original location if redirected
 * @returns Matched route object
 */
match(raw: RawLocation, current?: Route, redirectedFrom?: Location): Route;

/**
 * Get all components that match a given route
 * @param to - Route to get components for (defaults to current route)
 * @returns Array of matched components
 */
getMatchedComponents(to?: RawLocation | Route): Component[];

Usage Examples:

// Resolve a route location
const resolved = router.resolve('/users/123');
console.log(resolved.href); // "/users/123"
console.log(resolved.route.params); // { id: '123' }

// Match a route
const route = router.match('/users/123');
console.log(route.matched); // Array of matched route records

// Get components for current route
const components = router.getMatchedComponents();

Route Management

Add and manage routes dynamically.

/**
 * Add a new route record to the router
 * @param route - Route configuration to add
 */
addRoute(route: RouteConfig): void;

/**
 * Add a new route record as child of existing route
 * @param parentName - Name of parent route
 * @param route - Child route configuration to add
 */
addRoute(parentName: string, route: RouteConfig): void;

/**
 * Add multiple routes (deprecated - use addRoute instead)
 * @param routes - Array of route configurations
 */
addRoutes(routes: RouteConfig[]): void;

/**
 * Get list of all active route records
 * @returns Array of all route records
 */
getRoutes(): RouteRecordPublic[];

Usage Examples:

// Add a new route
router.addRoute({ path: '/new-page', component: NewPage });

// Add a child route
router.addRoute('parent-route', { 
  path: 'child', 
  component: ChildComponent 
});

// Get all routes
const allRoutes = router.getRoutes();
console.log(allRoutes.length);

Router Lifecycle

Handle router initialization and errors.

/**
 * Add callback to be called when router has completed initial navigation
 * @param callback - Function to call when ready
 * @param errorCallback - Function to call if initial navigation fails
 */
onReady(callback: () => void, errorCallback?: ErrorHandler): void;

/**
 * Add global error handler for navigation errors
 * @param handler - Error handler function
 */
onError(handler: ErrorHandler): void;

Usage Examples:

// Wait for router to be ready
router.onReady(() => {
  console.log('Router is ready');
  // Safe to render app
}, (error) => {
  console.error('Router failed to initialize', error);
});

// Handle navigation errors
router.onError((error) => {
  console.error('Navigation error:', error);
});

Types

type ErrorHandler = (err: Error) => void;

type PluginFunction<T> = (Vue: any, options?: T) => void;

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

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

interface RouteRecordPublic {
  path: string;
  components: Dictionary<Component>;
  instances: Dictionary<Vue>;
  name?: string;
  redirect?: RedirectOption;
  meta: any;
  beforeEnter?: NavigationGuard;
  props: boolean | Object | RoutePropsFunction | Dictionary<boolean | Object | RoutePropsFunction>;
}

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