'Why is this.$route.params null?

I want to pass data to another page and I use the following code:

  this.$router.push({ path: '/guard/foreigner-list', params: data});

Then I expect item is equal to data, but item is null

let item = this.$route.params;


Solution 1:[1]

You did not posted the entire code that is related to the process of changing route. But according to Vue Router documentation:

params are ignored if a path is provided, which is not the case for query, as shown in the examples. Instead, you need to provide the name of the route or manually specify the whole path with any parameter

So if you have defined a route called user in your router.js file like below:

import User from "../views/User"

const routes = [
  { 
    path: '/user/:id',
    name: 'User',
    component: User
  }
]

Then you can navigate programmatically from Home.vue to User.vue with the codes below:

Home.vue:

<template>
  <div class="home">
    <button @click="navigFunc">click to navigate</button>
  </div>
</template>

<script>

export default {
  name: 'Home',
  methods: {
    navigFunc: function () {
      const id = '123';
      // using "name" not "path"
      this.$router.push({ name: 'User', params: { id } });
    }
  }
}
</script>

User.vue:

<template>
<section>
  <h1>User page</h1>
</section>
</template>

<script>
export default {
  name: "User",
  mounted() {
  /* access the params like this */
    console.log(this.$route.params)
  }
}
</script>

<style scoped>

</style>

Notice that the variable I defined (id), is the same as the params that was defined in router.js (path: '/user/:id').

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hamid-davodi