Home > Enterprise >  Vuetify pagination not cycling through on button click
Vuetify pagination not cycling through on button click

Time:01-24

I am having trouble implementing Veutify's pagination component to cycle through my array.

<template>
  <div >
    <div v-for="(item, index) in pagedAssets" :key="`asset_index_${index}`">
      {{ item }}
    </div>
    <v-pagination
      v-model="pageNo"
      :length="numPages"
    ></v-pagination>
  </div>
</template>
<script setup>
let pageSize = 4;
let pageNo = 1;
let assets = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"];

const numPages = computed(() => {
  // calculate the number of pages we have
  return Math.ceil(assets.length / pageSize);
});

const pagedAssets = computed(() => {
  // get the start index for your paged result set.
  // The page number starts at 1 so the active item in the pagination is displayed properly.
  // However for our calculation the page number must start at (n-1)
  const startIndex = (pageNo - 1) * pageSize;

  // create a copy of your assets list so we don't modify the original data set
  const data = [...assets];

  // only return the data for the current page using splice
  return data.splice(startIndex, pageSize);
});
</script>

I am expecting when cycling through that the items will update.

CodePudding user response:

You need pageNo to be reactive, you can achieve that by making it a ref instead. You can read more about it here: https://vuejs.org/guide/essentials/reactivity-fundamentals.html

Here is a working example for your specific case: Playground

CodePudding user response:

pageNo is a v-model variable so it should be reactive but you are using it as a static variable that's why it is not updating. you need to use ref to make it reactive.

Replace your script with this-

<script setup>
import { computed, ref } from "vue";
  
let pageSize = 4;
let pageNo = ref(1);
let assets = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"];

const numPages = computed(() => {
  // calculate the number of pages we have
  return Math.ceil(assets.length / pageSize);
});

const pagedAssets = computed(() => {
  // get the start index for your paged result set.
  // The page number starts at 1 so the active item in the pagination is displayed properly.
  // However for our calculation the page number must start at (n-1)
  const startIndex = (pageNo.value - 1) * pageSize;

  // create a copy of your assets list so we don't modify the original data set
  const data = [...assets];

  // only return the data for the current page using splice
  return data.splice(startIndex, pageSize);
});
</script>
  • Related