Primoz Rome
Primoz Rome

Reputation: 11021

Nuxt refresh router view when router :id parameter changes

My Nuxt app loads a link and it's child view on the route http://127.0.0.1/user/:id. I put the API calls for the user in mounted hook of the router view.

If route id changes, mounted is not triggered anymore because the child view is already loaded. I ended up with solution - watch the $route.params.id and moved the API call from mounted to this watcher.

  watch: {
    $route() {
      this.getRows()
    }
  }

Is there a better way to do this?

Upvotes: 1

Views: 3575

Answers (1)

Vinicius Santin
Vinicius Santin

Reputation: 620

Solution 1

Force the reload when the route changes defining a :key for the <nuxt-child>, like this:

<nuxt-child :key="$route.fullPath"></nuxt-child>

Solution 2

Put the API call to load the user in a watch to the id coming from the URL instead to mounted, you can use immediate: true to call it in the fist load.

export default {
  data() {
    return {
        user: null
    }
  },
  asyncData({ params }) {
    return {
      id: params.id
    }
  },
  watch: {
    id: {
      immediate: true,
      handler(id) {
        //Call the API to get the user using the id
      }
    }
  }
}

Upvotes: 7

Related Questions