• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

98
Vistas
¿Cómo hacer un cargador infinito en Nuxt?

hola, quiero mostrar datos después de cargar infinitamente mis datos enviados por asyncData a la página y la página de identificación como esta

Page

 <script> export default { async asyncData({ $axios, store }) { const customerId = store.getters['user/auth/customerId'] if (!customerId) { return } const products = await customerApi.getProducts( { $axios }, customerId, this.page ) return { products, } }, data() { return { page: 1, } }, } </script>

Tengo los datos de la primera pagina. products es el envío de datos de accesorios en mi plantilla. en mi plantilla agrego una carga infinita

template

 <template> <generic-button v-if="!viewMore" inline @click="viewMore = true"> see more </generic-button> <client-only v-else> <infinite-loading :distance="800" force-use-infinite-wrapper @infinite="infiniteHandler" ></infinite-loading> </client-only> </template> <script> export default { components: { InfiniteLoading: () => process.client ? import('vue-infinite-loading') : Promise.resolve({ render: (h) => h('div') }), }, props: { products: { type: Array, required: true, }, }, data() { return { page: 1, } }, methods: { infiniteHandler($state) { // the method that will look for the data when the pagination changes }, }, } </script>

Me gustaría que cuando se inicie la paginación, vuelva a iniciar la solicitud asyncData cambiando el parámetro de la página a +1 y muestre los datos.

gracias

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Realmente no soy un gran admirador del paquete vue-infinite-loading , pero aun así logré hacerlo funcionar.

Aquí está el resultado final con la relación padre/hijo que deseaba.

parent page

 <template> <div> <nuxt-link :to="{ name: 'redirect' }"> Go to another page and come back to have this one triggered </nuxt-link> <child ref="child" :users="users" @fetchMore="callApi"></child> </div> </template> <script> export default { name: 'ParentPage', async asyncData({ $axios }) { const { data } = await $axios.$get( 'https://reqres.in/api/users?per_page=2&page=1' ) return { users: data } }, methods: { async callApi(newPageAsked) { const { data: newUsers } = await this.$axios.$get( `https://reqres.in/api/users?per_page=2&page=${newPageAsked}` ) console.log('new users fetched? ', newUsers) if (newUsers.length) { // if API got some new users, add them to the current list this.users = [...this.users, ...newUsers] // tell `infinite-loading` component that the fetch was successful this.$refs.child.$refs.infiniteLoader.stateChanger.loaded() } else { // if the API do not have anymore users to fetch this.$refs.child.$refs.infiniteLoader.stateChanger.complete() } }, }, } </script>

Child.vue

 <template> <div class="small-height"> <div v-for="user in users" :key="user.id"> <p class="user"> <span>{{ user.first_fame }}</span> <span>{{ user.last_name }}</span> <br /> <span>{{ user.email }}</span> <br /> <img :src="user.avatar" /> </p> </div> <infinite-loading ref="infiniteLoader" @infinite="infiniteHandler" ></infinite-loading> </div> </template> <script> import InfiniteLoading from 'vue-infinite-loading' export default { name: 'Child', components: { InfiniteLoading, }, props: { users: { type: Array, default: () => [], }, }, data() { return { page: 1, } }, methods: { infiniteHandler($state) { this.page += 1 this.$emit('fetchMore', this.page) }, }, } </script> <style scoped> .small-height { height: 200px; border: 2px solid red; width: 400px; overflow-y: auto; } .user { height: 200px; } </style>

¡Aquí está el repositorio de github para este y la versión alojada se puede encontrar aquí !

He agregado comentarios y si inspecciona la pestaña Red, debería tener suficiente información para ver qué está sucediendo.
He usado reqres.in para simular una API paginada.

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda