Hi everybody i\'m trying to watch on route changes in my nuxt js app.
Here my middleware:
export default function ({ route }) {
return route; but
First thing, context.route
or it's alias this.$route
is immutable object and should not be assigned a value.
Instead, we should use this.$router
and it's methods for programmatic navigation or <nuxt-link>
and <router-link>
.
As I understand, you need to render the same route, but trigger asyncData
hook in order to update component's data. Only route query is changed.
Correct way to navigate to the same page but with different data is to use link of such format:
<nuxt-link :to="{ name: 'index', query: { start: 420 }}"
Then you can use nuxt provided option watchQuery on page component and access that query inside asyncData
as follows:
watchQuery: true,
asyncData ({ query, app }) {
const { start } = query
const queryString = start ? `?start=${start}` : ''
return app.$axios.$get(`apps/${queryString}`)
.then(res => {
return {
info: res.results,
nextPage: res.next,
prevPage: res.prev
}
})
},
This option does not require usage of middleware
. If you want to stick to using middleware functions, you can add a key
to layout or page view that is used. Here is an example of adding a key
to default layout:
<nuxt :key="$route.fullPath" />
This will force nuxt
to re-render the page, thus calling middlewares and hooks. It is also useful for triggering transitions when switching dynamic routes of the same page component.