SoFunction
Updated on 2025-04-13

Example of method usage in Vue Router

Preface

Methods are used to parse routing information in front-end routing libraries (such as Vue Router). It accepts a routing object or path and returns an object containing parsed routing information. This object usually containshrefroutelocationetc.

Usage summary

  • Method signature

    (location, currentLocation, append)
    
    • location: The target route to be parsed can be a path string or a route object.
    • currentLocation(Optional): The current route location, default to the currently activated route.
    • append(Optional): Whether to append the target path after the current path.
  • Return value

    • Returns an object that usually contains the following properties:
      • href: parsed URL string.
      • route: The parsed route object.
      • location: The parsed target position object.

Sample code

Here is an example using Vue Router that shows how to usemethod:

import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/';
import About from './components/';

// Define the routeconst routes = [
  { path: '/', component: Home, name: 'home' },
  { path: '/about', component: About, name: 'about' },
];

// Create a router instanceconst router = createRouter({
  history: createWebHistory(),
  routes,
});

// Use the parse routeconst routeData = ({
  name: 'about', // Or path: '/about'});

(); // Output the parsed URL, for example "/about"(); // Output the parsed routing object(); // Output the parsed target position object
// Open the parsed URL in the new tab(routeData?.href, '_blank');

Detailed explanation

  • Define the route

    • Two routes are defined:/CorrespondingHomeComponents,/aboutCorrespondingAboutComponents.
  • Create a router instance

    • usecreateRouterandcreateWebHistoryCreate a router instance and pass in the defined route.
  • Analyze the route

    • useMethods resolve target routes, and the route name is used hereabout
    • Returns an object containing the parsed URL (href), routing object (route) and target position object (location)。
  • Use parsing results

    • Output the parsed URL, route object, and destination location object.
    • useOpen the parsed URL in the new tab.

Things to note

  • Methods are very useful, especially when you need to dynamically generate links or navigate in your code.
  • Ensure incominglocationThe object is a valid route path or route name, otherwise the resolution result may be incorrect.
  • The returned object can be used to generate navigation links, redirects, and other operations.