乐闻世界logo
搜索文章和话题

How to watch on Route changes with Nuxt and asyncData

1个答案

1

In applications using Nuxt.js for server-side rendering, it's common to handle asynchronous data at the component or page level. The asyncData method is a special lifecycle hook provided by Nuxt.js that enables asynchronous fetching or processing of data before setting the component's data. This method is invoked before each component load, and a typical use case involves fetching data based on route changes.

How to Monitor Route Changes:

In Nuxt.js, if you need to re-invoke asyncData when the route changes to update page data, you can leverage the watchQuery parameter. The watchQuery parameter is a boolean or array that allows you to specify which query parameters should trigger a re-invocation of the asyncData method.

Example:

Suppose you have a news list page that depends on the page query parameter in the URL. Whenever the user changes the page number, you want to re-fetch the news data. This can be implemented by setting watchQuery.

javascript
export default { watchQuery: ['page'], async asyncData({ query, $axios }) { const page = query.page || 1; try { const { data } = await $axios.get(`https://api.example.com/news?page=${page}`); return { news: data.news }; } catch (error) { return { news: [] }; } }, data() { return { news: [] }; } }

Detailed Explanation:

  1. watchQuery: In this example, we set watchQuery to monitor the page query parameter. This means that whenever the page parameter in the URL changes, the asyncData method is re-invoked.

  2. asyncData method: This method receives a context object containing the query parameter. We extract the current page number from query and use it to request news data for that specific page.

  3. $axios: In the example, we use the $axios module to send HTTP requests. This is a standard approach in Nuxt.js for performing HTTP requests, built upon the axios library.

  4. Error handling: During data requests, we employ the try...catch structure to manage potential errors. If the request fails, we set the news array to an empty array.

Using watchQuery effectively responds to changes in route query parameters, making the application more flexible and responsive to user interactions. This is particularly valuable for creating dynamically updated applications, especially when handling pagination, filtering, or search functionalities.

2024年7月5日 09:55 回复

你的答案