← Blog
29 Nov 2026Vue 3PaginationState ManagementData Tables

Vue Pagination: Keep Filters, Sorting, and Deletes in Sync

Keep Vue pagination correct when filters, sorting, page size, or records change. Build parent-owned state, clamp invalid pages, and handle empty results.

Vue Pagination: Keep Filters, Sorting, and Deletes in Sync

TL;DR

For reliable pagination in Vue, keep page, filters, sorting, and page size in one application-owned query. Reset to page 1 when the query changes. When records disappear, preserve the current page if it remains valid, otherwise clamp it to the last available page. Derive the displayed records from that reconciled page, and handle zero results separately from navigation.

A table can have perfectly functional Previous and Next buttons and still show the wrong records. Open its last page, apply a restrictive filter, and the old page number may now point beyond the results. Delete the only record on that page and the same failure appears without any filter changing.

Sorting introduces a different problem: it usually leaves the page count unchanged, but changes which records occupy each page.

We’ll build a focused Vue pagination example that handles these transitions together. The goal is not another pagination-control design. It is a consistent relationship between the query, the page indicator, and the records actually displayed.

Table of contents

Before you start

Use an existing Vue 3 application that compiles single-file components. The example uses JavaScript, the Composition API, and native form controls. No additional pagination package is required.

You’ll need records with stable, unique IDs and a decision about who owns the complete result set. Our example generates 21 local records. It does not implement API persistence, authorization, or route synchronization. Keep those application-specific concerns separate when integrating it.

This distinction matters: client-side pagination assumes the complete candidate dataset is available locally, while server-side pagination receives an already paginated result. See the definitions in TanStack Table’s v8 pagination guide.

1. Choose reset and clamp rules before wiring controls

I recommend treating a changed query differently from a changed collection.

Event Policy used here Reason
Search or filter changes Reset to page 1 The user requested a different result set.
Sort changes Reset to page 1 The new ordering should begin at its starting point.
Page size changes Reset to page 1 Page boundaries now describe different record ranges.
Records are deleted or refreshed Keep the page, then clamp if necessary Preserve the browsing position when it is still valid.
No records match Keep internal page 1, show an empty state There is no result page to navigate.

Sorting alone does not make a page numerically out of range. Resetting after a sort is a product policy, not a mathematical requirement. If your product must preserve the selected record instead, locate that record in the new ordering and derive its page explicitly.

For this guide, the processing order is filter, sort, count, reconcile the page, then slice. Slicing before filtering can produce a nearly empty page while matching records remain elsewhere. Sorting only the slice similarly changes the meaning of the sort.

Pagination decision flow: reset for query changes, clamp after record removal, and show an empty state when no records match.

Check: describe what should happen when page 5 becomes invalid. If the answer depends on whether the user filtered or deleted a record, the application needs both policies rather than one universal reset watcher.

2. Build one parent-owned Vue pagination model

Save this as AccountsTable.vue, then import and render it in your existing application. The component owns the query that a child table or pagination control would receive.

Vue’s reactivity fundamentals document refs, template unwrapping, and nextTick. Its computed-property guidance supports deriving results without mutating query state inside a getter. The example uses those Vue 3 APIs directly.

<script setup>
import { computed, nextTick, ref, watch } from 'vue'

const records = ref(Array.from({ length: 21 }, (_, index) => ({
  id: index + 1,
  name: `Account ${String(index + 1).padStart(2, '0')}`,
  status: index % 2 === 0 ? 'active' : 'paused',
})))

const query = ref({
  search: '',
  status: 'all',
  sort: 'asc',
  pageSize: 5,
  page: 1,
})
const resultsHeading = ref(null)

const matchingRows = computed(() => {
  const search = query.value.search.trim().toLowerCase()
  return records.value
    .filter(row =>
      row.name.toLowerCase().includes(search) &&
      (query.value.status === 'all' ||
        row.status === query.value.status)
    )
    .sort((a, b) => {
      const order = a.name.localeCompare(b.name) || a.id - b.id
      return query.value.sort === 'asc' ? order : -order
    })
})

const total = computed(() => matchingRows.value.length)
// One is an internal minimum, not a claim that empty results have a page.
const pageCount = computed(() =>
  Math.max(1, Math.ceil(total.value / query.value.pageSize))
)
const page = computed(() =>
  Math.min(Math.max(query.value.page, 1), pageCount.value)
)
const start = computed(() => (page.value - 1) * query.value.pageSize)
const visibleRows = computed(() =>
  matchingRows.value.slice(start.value, start.value + query.value.pageSize)
)

function changeQuery(patch) {
  query.value = { ...query.value, ...patch, page: 1 }
}

function goToPage(next) {
  if (!Number.isInteger(next)) return
  query.value = {
    ...query.value,
    page: Math.min(Math.max(next, 1), pageCount.value),
  }
}

// Reconcile stored state when record changes alter the available pages.
watch(pageCount, () => {
  if (query.value.page !== page.value) goToPage(page.value)
})

async function remove(id) {
  records.value = records.value.filter(row => row.id !== id)
  await nextTick()
  resultsHeading.value?.focus()
}
</script>

<template>
  <section aria-label="Account directory">
    <h2 ref="resultsHeading" tabindex="-1">Accounts</h2>

    <div class="controls">
      <label>
        Search accounts
        <input
          type="search"
          :value="query.search"
          @input="changeQuery({ search: $event.target.value })"
        />
      </label>
      <label>
        Status
        <select
          :value="query.status"
          @change="changeQuery({ status: $event.target.value })"
        >
          <option value="all">All statuses</option>
          <option value="active">Active</option>
          <option value="paused">Paused</option>
        </select>
      </label>
      <label>
        Name order
        <select
          :value="query.sort"
          @change="changeQuery({ sort: $event.target.value })"
        >
          <option value="asc">Ascending</option>
          <option value="desc">Descending</option>
        </select>
      </label>
      <label>
        Rows per page
        <select
          :value="query.pageSize"
          @change="changeQuery({ pageSize: Number($event.target.value) })"
        >
          <option :value="5">5</option>
          <option :value="10">10</option>
        </select>
      </label>
    </div>

    <button type="button" @click="changeQuery({ search: '', status: 'all' })">
      Clear filters
    </button>
    <p aria-live="polite">
      {{ total }} matching accounts.
      <span v-if="total">
        Showing {{ start + 1 }} to {{ start + visibleRows.length }}.
        Page {{ page }} of {{ pageCount }}.
      </span>
    </p>

    <table v-if="total">
      <caption>Matching accounts</caption>
      <thead>
        <tr>
          <th scope="col">Name</th>
          <th scope="col">Status</th>
          <th scope="col">Action</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="row in visibleRows" :key="row.id">
          <td>{{ row.name }}</td>
          <td>{{ row.status }}</td>
          <td>
            <button
              type="button"
              :aria-label="`Delete ${row.name}`"
              @click="remove(row.id)"
            >Delete</button>
          </td>
        </tr>
      </tbody>
    </table>
    <p v-else>No matching accounts. Try clearing the filters.</p>

    <nav v-if="total && pageCount > 1" aria-label="Account pages">
      <button type="button" :disabled="page === 1" @click="goToPage(page - 1)">
        Previous
      </button>
      <button
        type="button"
        :disabled="page === pageCount"
        @click="goToPage(page + 1)"
      >Next</button>
    </nav>
  </section>
</template>

<style scoped>
.controls { display: flex; flex-wrap: wrap; gap: 1rem; margin-block: 1rem; }
label { display: grid; gap: .25rem; }
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
th, td { padding: .5rem; text-align: left; border-bottom: 1px solid #ddd; }
button, input, select { font: inherit; }
button { margin-inline-end: .5rem; }
:focus-visible { outline: 2px solid #2457c5; outline-offset: 2px; }
</style>

The example sorts the new array returned by filter, not the source records. It also uses record IDs as row keys. Both decisions follow Vue’s list-rendering guidance: avoid mutating a source array during computed sorting, and use stable identity when records move.

Expected result: initially, the table shows Accounts 01 through 05 and reports page 1 of 5. If it renders every account, check that v-for uses visibleRows, not records or matchingRows.

3. Keep query changes and page reconciliation separate

changeQuery replaces the query with a new object containing both the changed field and page: 1. It preserves the other fields. Changing status therefore does not erase search text or sorting, while clearing filters deliberately preserves sort and page size.

The controls use native input and change events, following Vue’s event-handling syntax. Converting the page-size selection to a number keeps the pagination arithmetic independent of form-control string values.

The page computed value immediately supplies a bounded page for slicing. The watcher then reconciles the stored query when the available page count changes. Vue documents that default watcher callbacks run before their owning component’s DOM update. The slice does not depend on waiting for that callback to become valid.

Do not move the assignment into the computed getter. Keep derivation pure and mutation explicit.

When extracting children, retain this ownership boundary: children request changes; the parent applies query policy. Our pagination component documentation makes the same distinction: bounding a control’s displayed page does not reconcile the application’s query or fetch records for it.

Check: navigate forward, change Status to Active, and confirm the indicator returns to page 1 while the selected name order remains unchanged.

4. Handle deletion and empty results without losing context

Reload the demo, keep five rows per page, and navigate to page 5. Only Account 21 should remain. Delete it.

There are now 20 records and four pages. The application clamps the current page from 5 to 4, displaying Accounts 16 through 20. It does not reset the user to the beginning of the directory.

Deleting Account 21 reduces five pages to four, so pagination moves to page 4 and displays Accounts 16 through 20.

Deleting a record from page 2 should leave page 2 selected while that page still exists. Earlier records may shift into the displayed range, but the search, status, and sort choices remain intact.

That is page-position preservation, not record anchoring. If your workflow must keep a particular account visible during background updates, store its ID and deliberately relocate it after the update. A page number alone cannot express that requirement.

For an empty result, the internal minimum of 1 prevents invalid offsets. The interface does not announce “page 1 of 1”: it hides navigation and displays an empty-state message. Clearing filters restores the query without resurrecting deleted local records.

The deletion handler also waits for nextTick before focusing the stable results heading. That avoids leaving focus on a removed row button. The demo deletes locally and immediately; a production mutation needs a defined success, failure, and possibly rollback policy.

Troubleshooting: an empty page after deletion usually means the slice still uses the unbounded requested page, or the total was not recomputed from the current matching records.

5. Apply the same contract to API-backed results

Do not copy the local array-length calculation into a server-paginated table. The response length describes the current page, not the complete filtered result. A numbered paginator needs a total or page count supplied by the backend, as explained in TanStack’s pagination guide.

Keep the query model, but change the reconciliation sequence:

  1. Apply a filter, sort, or size change together with the page reset.
  2. Request that complete query, rather than updating page and filters through independent fetch paths.
  3. Accept only a response belonging to the current query generation.
  4. Use its authoritative total to check whether the requested page still exists.
  5. If necessary, update the page and request the corrected page before treating its records as current.

For example, if a deletion makes page 5 invalid and the response reports four remaining pages, setting the indicator to 4 is insufficient. You still need page 4’s records, unless the API already returned that corrected page and identified it explicitly.

Vue’s watcher cleanup documentation describes cancelling stale asynchronous work. For production requests, I also recommend checking request identity before committing records, totals, errors, or loading completion. A slow old response must not replace a newer query’s state. Avoid synchronous fetch watchers that observe intermediate field changes; Vue warns that synchronous watchers are not batched.

Keep filtering and sorting authoritative on the same side as pagination. A local sort of one fetched page is not a global sort, a limitation explicitly described in TanStack’s v8 sorting guide.

If the API exposes only a next-page signal, do not invent a last page. Use navigation that matches that contract. Keep loading and request failure separate from a successful empty response.

For shareable views, serialize the meaningful query fields together. Validate incoming page numbers as positive integers and page size against an allowed set. Restore route state as a distinct operation, rather than calling the filter-change handler that intentionally resets page 1.

Check: delay two different filter requests so the older one finishes last. Its records and total must not appear under the newer filter.

6. Verify transitions, not just button clicks

Start each destructive check with a fresh copy of the 21 generated records. These checks describe expected behavior, not executed test results.

Scenario Expected result
Initial load, five rows per page Accounts 01 to 05, page 1 of 5.
Go to page 5, then select Active Page 1, with 11 matching active accounts.
Change ascending order to descending Page 1 begins with Account 21 in the unfiltered dataset.
On page 5, delete Account 21 Page 4 shows Accounts 16 to 20.
Delete a row from a still-valid middle page The current page remains selected.
Search for a nonexistent name Empty state, zero matches, no pagination navigation.
Change five rows per page to ten Page 1, with three pages before any deletions.
Clear filters after a search Search and status reset; sorting and page size remain selected.

For component tests, wait for Vue’s update cycle before asserting the DOM or reconciled stored page. Also test deletion focus, keyboard-operated controls, and the relationship between the announced page and the rendered record IDs.

For remote integration, add an out-of-range restored URL, a failed deletion, an unavailable total, and overlapping requests. Test background changes that preserve a valid page as well as those that remove it.

For a visual introduction to reusable pagination components, the following instructional walkthrough is a useful companion. Use the Vue 3 implementation above for this guide’s reset-and-clamp behavior rather than assuming the video implements the same policy.

FAQ

Should every data refresh reset Vue pagination?

Not necessarily. In this model, a refresh preserves the page while it remains valid. An explicit query change resets it. Resetting every refresh would send users back to the beginning during unrelated background updates.

Can a pagination component fix an invalid parent page automatically?

Do not assume so. A control can display a bounded number while the application still requests an invalid page. Check the component contract and reconcile the state used for both navigation and fetching. DOM Studio documents that responsibility in its application-ownership guidance linked above.

Put the model into your resource table

You now have one query owner and explicit rules for resets, clamping, deletion, and empty results. The useful next step is to replace the generated records with your resource data while preserving those transitions.

Inspect our controlled pagination examples when replacing the native navigation. Keep the application responsible for the query, then verify that the control, request parameters, result count, and displayed records describe the same page.

Sources

Recommended Reads