Why and how would you pass parameters to a Vue application?
You might have seen URLs that pass parameters to whatever front-end / back-end logic that is processing them. This will be something akin to -
https://myapp.com/accounts/1
https://myapp.com/accounts/1/todo/2
https://myapp.com/accounts?id=1
https://myapp.com/accounts?query=abc&role=my
id
, query
, role
are parameters passed in the URL. The receiving function can have access to the parameters and values, and have processing logic based on values.
URL params are heavily used in some of the modern headless CMS applications (e.g. Strapi). You can pass a whole lot of stuff against URL and the server has out of the box support to respond to the values. Even in some of the older APIs will have support to referring to a specific resource with id
.
So, where should and can you use Vue parameters?
- Application can display multiple accounts, but needs to filter account based on the value provided in URL (these are typically used to display specific account details on drilling down on a link for example)
- Enable filtering logic that is passed as context from another view. For example, filter accounts on state when drilling down from a chart showing sales numbers by states
- Pass an action to be done automatically. For example, assign a service request to user when user drills-down on a record in the list of unassigned service requests
- Navigate to or activate a component within the view. For example, show the
Activity
tab in theAccount Detail
view when drilling down fromActivity
page
How to pass params in the URL in Vue? Use dynamic route matching in router, and get your components ready to receive those parameters.
To pass id as a dynamic parameter, change path in router.js
-
|
|
The component can now do the following to receive the id -
|
|
Or, receive multiple parameters-
|
|
To catch params passed through ?
, you just need to do access route query. This does not need a change to router.js
.
|
|
Receive parameters in component -
|
|