Home >Web Front-end >Vue.js >Usage of params and query in vue
In Vue, params and query are used to access dynamic routing fragments and query string parameters. The params object contains the values of the dynamic route fragment, while the query object contains the parameter and value pairs in the query string. params is part of the route, but query is not, which affects route matching. You can access params and query through the $route object and use them to pass data when navigating.
Usage of params
and query
in Vue
In Vue routing, params
and query
are two closely related concepts:
params
params
Object contains the value of the dynamic fragment of the current route. Dynamic fragments are named fragments that use the :
prefix in the route's path, such as /user/:id
.
<code class="js">const User = { template: '<p>User ID: {{ $route.params.id }}</p>' }</code>
When a route matches /user/123
, $route.params
will contain the following objects:
<code class="js">{ id: '123' }</code>
query
query
object contains the parameters in the current route query string. The query string is the parameter and value pair after the ?
number in the URL, such as ?page=2&sort=desc
.
<code class="js">const SearchResults = { template: '<p>Page: {{ $route.query.page }}</p>' }</code>
When a route matches /search?page=2&sort=desc
, $route.query
will contain the following objects:
<code class="js">{ page: '2', sort: 'desc' }</code>
Distinguish between params and query
One key difference between params
and query
is that params
is part of the route, while query
No. This means params
will affect route matching, but query
will not. For example, the route /user/:id
will only match URLs with valid id
parameters. However, the /search
route will match any URL with or without a query string.
Using params and query
You can access params
and query
through the $route
object object. For navigation, you can use the $router.push
or $router.replace
methods, both of which support passing params
or query
object.
<code class="js">// 使用 params 导航 this.$router.push({ name: 'user', params: { id: '123' } }) // 使用 query 导航 this.$router.push({ name: 'search', query: { page: 2, sort: 'desc' } })</code>
Summary
params
and query
are important concepts in Vue routing and are used to access dynamic routing fragments and Query string parameters. Understanding the difference between the two is crucial to using Vue routing effectively.
The above is the detailed content of Usage of params and query in vue. For more information, please follow other related articles on the PHP Chinese website!