“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”


preface

We often have the need to pass some data when switching components, which involves routing parameters.

Vue-router passes two kinds of parameters: ① programmatic navigation router.push. ② Declarative navigation<router-link>

Programmatic navigation router. Push

Pass the value -name through the params attribute
// In the route configuration file
{
     path: '/detail'.name: 'Detail'.component: Detail
   }
// Jump to the page
this.$router.push({
  name: 'Detail'.params: {
    name: 'Joe'.id: 1,}})// Get the parameter object on the page after the jump
this.$route.params 
Copy the code

Note: The named route passes parameters using params. It is important to note that params is not query. Use Params when the destination page receives the passed parameter

Pass the value -path through the query attribute
// In the route configuration file
{
     path: '/detail'.name: 'Detail'.component: Detail
   }
// Jump to the page
this.$router.push({
  path: '/detail'.query: {
    name: 'Joe'.id: 1,}})// Get the parameter object on the page after the jump
this.$route.query 
Copy the code
Through dynamic routing
// Configure dynamic routes in the route configuration file
{
     path: '/detail/:id'.name: 'Detail'.component: Detail
   }
// Jump to the page
var id = 1;
this.$router.push('/detail/' + id)
 
// Get parameters on the page after the jump
this.$route.params.id
Copy the code

Declarative navigation

Declarative navigation is used much the same as programmatically.

Pass the value -name through the params attribute
<router-link :to="{ name: 'news', params: { userId: 1111}}">click to news page</router-link>
Copy the code
Pass the value -path through the query attribute
<router-link :to="{ path: '/news', query: { userId: 1111}}">click to news page</router-link>
Copy the code
Through dynamic routing
 <router-link :to="'/user/'+userid" tag="button">The user</router-link>
Copy the code

$route and $routerThe difference between

  • $routerFor a VueRouter instance that wants to navigate to a different URL, use$router.pushmethods

– $route indicates that the name, path, query, and params can be obtained from the current Router jump object

A small summary

  • The dynamic route and query attribute pass page refresh parameters are not lost, but the Params are
  • Dynamic routing is usually used to pass only one parameter (such as the id of the detail page). Query and params can pass one parameter or multiple parameters.
  • Get parameter pass$route objects.$route.queryand$route.parmas