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 contains
href
、route
、location
etc.
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.
-
- Returns an object that usually contains the following properties:
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:
/
CorrespondingHome
Components,/about
CorrespondingAbout
Components.
- Two routes are defined:
-
Create a router instance:
- use
createRouter
andcreateWebHistory
Create a router instance and pass in the defined route.
- use
-
Analyze the route:
- use
Methods resolve target routes, and the route name is used here
about
。 -
Returns an object containing the parsed URL (
href
), routing object (route
) and target position object (location
)。
- use
-
Use parsing results:
- Output the parsed URL, route object, and destination location object.
- use
Open 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 incoming
location
The 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.