how to send data to another page in nuxt.js in javascript

To send data to another page in Nuxt.js, you can use routing parameters.

First, define the parameter in the URL of the target page by adding a colon and a name for the parameter in the page's route definition in the Nuxt.js config file (nuxt.config.js) or in the page's .vue file:

index.tsx
// nuxt.config.js
export default {
  routes: [
    {
      path: '/user/:userId',
      component: 'pages/user/_userId.vue'
    }
  ]
}
136 chars
10 lines
<!-- pages/user/_userId.vue -->
<script>
export default {
  created() {
    console.log(this.$route.params.userId) // prints the userId from the URL
  }
}
</script>
165 chars
9 lines

Then, when navigating to that page from another page, use the router.push method and pass the data as an object in the params option:

<script>
export default {
  data() {
    return {
      userId: 123
    }
  },
  methods: {
    goToUser() {
      this.$router.push({
        path: `/user/${this.userId}`,
        params: { data: { foo: 'bar' } }
      })
    }
  }
}
</script>
245 chars
18 lines

In the target page, you can access the data passed in the params option using this.$route.params:

<!-- pages/user/_userId.vue -->
<script>
export default {
  created() {
    console.log(this.$route.params.userId) // prints the userId from the URL
    console.log(this.$route.params.data.foo) // prints 'bar'
  }
}
</script>
226 chars
10 lines

gistlibby LogSnag