Last active
December 13, 2022 13:55
-
-
Save prpanto/bd3bb2d9b0cb1fd8afe55f94335891de to your computer and use it in GitHub Desktop.
Infinity loading in InertiaJS and VueJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<template v-for="post in allPosts" :key="post.id"> | |
<h1>{{ post.title }}</h1> | |
<p>{{ post.content }}</p> | |
</template> | |
<span ref="loadMore"/> | |
</template> | |
<script setup> | |
import { onMounted, ref } from 'vue' | |
import { Inertia } from '@inertiajs/inertia'; | |
import { useIntersectionObserver } from '@vueuse/core' | |
const props = defineProps({ | |
posts: Object | |
}); | |
const allPosts = ref(props.posts.data); | |
const loadMore = ref(); | |
function loadMorePosts() { | |
if (props.posts.next_page_url === null) return | |
Inertia.get(props.posts.next_page_url, {}, { | |
preserveState: true, | |
preserveScroll: true, | |
only: ['posts'], | |
onSuccess: () => { | |
allPosts.value = [...allPosts.value, ...props.posts.data]; | |
window.history.replaceState({}, page.title, "/post"); | |
} | |
}); | |
} | |
onMounted(() => useIntersectionObserver( | |
loadMore.value, | |
([{ isIntersecting }]) => isIntersecting && loadMorePosts(), | |
{ rootMargin: "-150px 0px 0px 0px" } | |
)); | |
</script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function index() { | |
$posts = Post::paginate(10); | |
return Inercia::render('Posts/INdex', ['posts', => $posts]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment