Dynamic Route Matching | vue router lifecycle
Veryoftenwewillneedtomaprouteswiththegivenpatterntothesamecomponent.Forexample,wemayhaveaUsercomponentwhichshouldberenderedforallusersbutwithdifferentuserIDs.InVueRouterwecanuseadynamicsegmentinthepathtoachievethat,wecallthataparam:jsimportUserfrom./User.vue//thesearepassedto`createRouter`constroutes=[//dynamicsegmentsstartwithacolon{path:/users/:id,component:User},]NowURLslike/users/johnnyand/users/jolynewillbothmaptothesameroute.Aparamisdenotedbyacolon:.Whenarouteismatched,thevalueofitspar...
Very often we will need to map routes with the given pattern to the same component. For example, we may have a User component which should be rendered for all users but with different user IDs. In Vue Router we can use a dynamic segment in the path to achieve that, we call that a param:
jsimport User from ./User.vue // these are passed to `createRouter` const routes = [ // dynamic segments start with a colon { path: /users/:id, component: User }, ]Now URLs like /users/johnny and /users/jolyne will both map to the same route.
A param is denoted by a colon :. When a route is matched, the value of its params will be exposed as route.params in every component. Therefore, we can render the current user ID by updating Users template to this:
vue<template> <div> <!-- The current route is accessible as $route in the template --> User {{ $route.params.id }} </div> </template>You can have multiple params in the same route, and t...