2
votes

I have a bunch of Vue components and I'm using Nuxt as the routing layer. My global layout is pretty standard:

<template>
  <nav>
    <nuxt-link to="/foo">foo</nuxt-link> | <nuxt-link to="/bar">bar</nuxt-link> | etc.
  </nav>

  <main>
    <nuxt />
  </main>
</template>

In each page, I update the query string when data in the vuex store changes. If the page is loaded server-side, I parse the query string to pre-load the necessary data into the store:

<template>
   <h1>foo</h1>
   <!-- forms and stuff -->
</template>

<script>
export default {
  data() {
    return {
      // static data
    }
  },

  computed: {
    fooStoreParams() {
      return this.$store.state.foo.params
    }
  },

  watch: {
    fooStoreParams: async function() {
      await this.$nextTick()

      let query = {}

      if (this.fooStoreParams.page > 1) {
        query.page = this.fooStoreParams.page
      }

      this.$router.push({ path: this.$route.path, query: query })
    }
  },

  async asyncData({ store, query }) {
    let params = {}

    let data = {
      form: {
        page: 1
      }
    }

    if (query.page) {
      data.form.page = query.page
      params.page = query.page
    }

    store.dispatch('foo/updateParams', params)
    await store.dispatch('foo/getStuffFromAPI')

    return data
  }
}
</script>

This works well, but there's a feature that I'm missing.

If I'm on already on /foo?page=2&a=1&b=2 and I click on the /foo link in the main navigation, nothing happens. This makes sense considering how Nuxt/vue-router works, but what I want to happen is for the page component to be reloaded from scratch (as if you had navigated from /bar to /foo).

The only ways I can think to do this are to either 1) do a server-side request (e.g. <b-link href="/foo">) if I'm already on /foo?whatever or 2) write a resetPage() method for each individual page.

Is there a way to just tell Nuxt to destroy and recreate the current page component?

2

2 Answers

0
votes

You need to use watchQuery in order to enable client-navigation for query-params:

watchQuery: ['page', 'a', 'b']

https://nuxtjs.org/api/pages-watchquery/

0
votes

If you have a component e.g

<titlebar :key="somekey" />

and the value of somekey changes the component re-renders. You could maybe work around this to achieve what you want. Read more here: https://michaelnthiessen.com/force-re-render/