To handle the deletion of the last item on a paginated page using Vue and Inertia.js, you can implement a watcher that observes changes to the meta.from property. When meta.from becomes null, it indicates that there are no items left on the current page, and you should redirect the user to the previous page. Here's a solution using Vue 3 and Inertia.js:
<script setup>
import { watch } from 'vue'
import { router } from '@inertiajs/vue3'
// Define the props that the component will receive
const props = defineProps({
meta: {
type: Object,
required: true
},
links: {
type: Object,
required: true
},
only: {
type: Array,
default: []
}
})
// Watch for changes in the meta.from property
watch(() => props.meta.from, (newValue) => {
// If meta.from is null, redirect to the previous page
if (newValue === null) {
router.visit(props.links.prev ?? props.links.first, {
preserveScroll: true
})
}
})
</script>
<template>
<!-- Pagination UI goes here -->
</template>
Explanation:
-
Props Definition: The component expects
metaandlinksas props.metacontains pagination information, andlinkscontains URLs for navigation. -
Watcher: The
watchfunction observes changes toprops.meta.from. If it becomesnull, it means the current page is empty after a deletion. -
Redirection: The
router.visitmethod from Inertia.js is used to navigate to the previous page (props.links.prev). If there's no previous page, it defaults to the first page (props.links.first). ThepreserveScroll: trueoption ensures that the scroll position is maintained during navigation.
This approach provides a seamless user experience by automatically handling pagination changes when items are deleted.