NanoNano
NanoNano

Reputation: 51

Route params value disappears after reload page in Nuxt JS

I use this.$router.push({name: 'nameComponent', params: {data:someObject}}) to switch pages. On the next page, params are detected when the page is first loaded. However, after reloading the page, params are no longer detected.

FYI, route configuration in Nuxt JS already uses history mode

Upvotes: 1

Views: 3053

Answers (1)

Thomas Kuhlmann
Thomas Kuhlmann

Reputation: 1003

You are using your router to share state between different components. On refreshing a route, the original data that was passed from page A to B is not retained - that behaviour is expected since you aren't accessing page A which is fetching the data.

If you want to be able to access data after a page refresh, you either need to fetch it again from the source in page B, cache it locally or change the way your components and routes work.

From Source

Fetching it from the source would mean you don't pass the actual data in the route, just the id and then fetch the data again in page B.

Downside

You might be fetching the same data twice

Local Storage

You can persist data you loaded in page A. You can either do this directly by

  1. saving directly to local storage
  2. using a library like localForage
  3. using Vuex and the vuex-persist plugin

In page B you could access your local storage and retrieve the data from there.

Downside

This would still require the user to have visited page A at some stage and if that was a long time ago, data might be outdated if the user keeps visiting page B directly. It also means that you'd have to check if the data exists since the user might have cleared the cache.

Adjusting component and route architecture

Probably the way to go. You can create a parent component that fetches the data, and two child components that get the data passed as props, e.g.:

// Routes 
cont routes = {
    path: '',
    name: 'parent',
    compoent: Parent.vue,
    children: [{
        path: '/pageA'
        name: 'pageA',
        component: PageA
      },
      {
        path: '/pageB'
        name: 'pageB',
        component: PageB
      }
    ]
// Parent.vue
<template>
 <router-view :user="user" />
</template>

<script>
  export default {
    data() {
      return {
        user: null
      }
    }
  },
  created() {
    ...fetch data
  }
</script>


// PageA.vue & PageB.vue

<template>
 ...
</template>

<script>
  export default {
    props: {
      user: {
        type: Object,
        require: true
      }
    }
  }
</script>

Upvotes: 3

Related Questions