"Customize the number of items displayed per page with Bootstrap Vue's perPage

I am currently working on a Vue project which you can view on codesandbox and utilizing bootstrap-vue.

Within the project, there are multiple columns containing cards along with pagination:

<template>

  <b-container>
    <b-row 
      :current-page="currentPage"
      :per-page="perPage">   

      <b-col cols="12" sm="4" class="my-1"
        v-for="item in items" 
          :key="item.id">

        <b-card           
          :bg-variant="item.variant"
          text-variant="white"
          header="item.title"
          class="text-center"
          >
          <p class="card-text">
            {{item.body}}
          </p>
        </b-card>  

      </b-col>

    </b-row>

    <b-row>
      <b-col md="6" class="my-1">
        <b-pagination :total-rows="totalRows" :per-page="perPage" v-model="currentPage" class="my-0" />
      </b-col>
    </b-row>
  </b-container>

</template>

I am currently looking for guidance on how to set the perPage property in bootstrap-vue for custom columns or rows similar to bootstraps table pagination functionality.

The desired outcome is to display 2 columns with cards per page using perPage: 2.

Question: Can anyone provide assistance on setting the bootstrap-vue perPage for custom columns or rows?

Answer №1

If you're looking to display 2 cards per page, I recommend using my solution that utilizes computed properties. In my code, I have implemented a feature called currentPageItems.

computed: {
   ...
   
   currentPageItems() {
          let totalItems = this.items.length;
      this.numOfPages = 0;
        for (let i = 0; i < totalItems; i = i + this.perPage) {
        this.paginated_items[this.numOfPages] = this.items.slice(
          i,
          i + this.perPage
        );
        this.numOfPages++;
      }
       
        return this.paginated_items[this.currentPage-1];
  
    }
    
    ...
  }

I also added these properties in the data():

paginated_items: {},
currentPageIndex:0,
numOfPages:0

In the template section, change items to currentPageItems

...
 <b-col cols="12" sm="4" class="my-1" v-for="item in currentPageItems" :key="item.id">
...

Here is the complete code snippet :

<template>

  <b-container>
    <b-row>   
    
      <b-col cols="12" sm="4" class="my-1"
        :key="index"
        v-for="(item, index) in currentPageItems" 
          >
        <b-card         
          :bg-variant="item.variant"
          text-variant="white"
          :header="item.title"
          class="text-center"
          >
          <p class="card-text">
            {{item.body}}
          </p>
        </b-card>  

      </b-col>

    </b-row>

    <b-row>
      <b-col md="6" class="my-1">
        <b-pagination :total-rows="totalRows" :per-page="perPage" v-model="currentPage" class="my-0" />
      </b-col>
    </b-row>
  </b-container>

</template>

<script>
const items = [
  {
    title: "Primary",
    body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    variant: "primary"
  },
  {
    title: "Secondary",
    body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    variant: "secondary"
  },
  {
    title: "Success",
    body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    variant: "success"
  },
  {
    title: "Info",
    body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    variant: "info"
  },
  {
    title: "Warning",
    body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    variant: "warning"
  },
  {
    title: "Danger",
    body: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    variant: "danger"
  }
];

export default {
  name: "MyBootstrapGrid",
  data() {
    return {
      items: items,
      currentPage: 1,
      perPage: 2,
      totalRows: items.length,
      paginated_items: {},
      currentPageIndex:0,
      numOfPages:0
    };
  },
  computed: {
    pageCount() {
      let total = this.totalRows,
        size = this.perPage;
      return Math.floor(total / size);
    },
      currentPageItems() {
          let totalItems = this.items.length;
      this.numOfPages = 0;
        for (let i = 0; i < totalItems; i = i + this.perPage) {
        this.paginated_items[this.numOfPages] = this.items.slice(
          i,
          i + this.perPage
        );
        this.numOfPages++;
      }
       
        return this.paginated_items[this.currentPage-1];
  
    }
  },
  methods: {}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

Answer №2

If I interpreted your message correctly, the next step for you would be to paginate the items. Feel free to check out this functioning Sandbox where I have included data for paginatedItems along with methods like paginate and onPageChange.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best practice for adding one string to the end of another?

So, is this the best way to concatenate strings in JavaScript? var str = 'Hello'; str += ' World'; While most languages allow for this method of string concatenation, some consider it less efficient. Many programming languages offer a ...

Is your custom login form in Web2py not submitting properly?

My attempt to customize the login form for web2py has hit a roadblock. Despite adding the necessary fields and submit button, nothing seems to be happening. Here's what the code in the form's view looks like: {{include 'web2py_ajax.html&apo ...

We are creating a table in JavaScript and mistakenly adding an unnecessary tbody

I am currently utilizing a combination of plain JavaScript and Jquery in order to dynamically generate a table. The issue arises when I attempt to use a for loop to iterate through the data obtained from an Ajax request, as it fails to create new rows. To ...

Which comes first in AngularJS: ng-include or ng-repeat?

What is the outcome if I have a template containing ng-repeat and include it using ng-include? Will the included template have the completed ng-repeat, or will it be included without the ng-repeat being complete (and then completed after inclusion)? ...

What is the process for configuring environment variables in a React application?

I have set up my React app to run on http://localhost:3000, and now I am looking to configure environment variables for different environments such as development, production, staging, and local. These are the URLs for my React app in various environments ...

Encountering a CORS issue specifically on the client side of a Next.js application when interacting with an API gateway

I've been struggling with this issue for a week now and can't seem to fully describe it. I have a FastAPI server running as a Lambda connected to API Gateway. https://i.stack.imgur.com/S5Zx9.png Both FastAPI and API Gateway have CORS enabled, b ...

A guide on managing Ngb Bootstrap carousel slide with a button in Angular

I encountered a situation like this: I need to implement a Ngb Bootstrap carousel with buttons for Previous and Next to control the slide images. Clicking on the Previous button should display the previous slide image, and clicking on the Next button shou ...

A guide on determining the return type of an overloaded function in TypeScript

Scenario Here is a ts file where I am attempting to include the type annotation GetTokenResponse to the function getToken. import { ConfigService } from '@nestjs/config'; import { google, GoogleApis } from 'googleapis'; import { AppCon ...

Creating a dynamic HTML table using Vue 3

My table is not showing the data I'm fetching from my API. Even though I can see the data in my console.log, it's not populating the table. Could there be an issue with how I'm calling the data to display in the table? <template> < ...

Is there a way for me to manipulate the RGB values of the canvas in such a manner that the Red and Green components of the gradient are determined by dividing the position of my mouse cursor

My homework assignment requires using RGB colors where the red value is set to 0, green is the x-coordinate divided by 2, and blue is the y-coordinate divided by 2. I've been trying to control the colors on a canvas using addColorStop functions, but I ...

Tips on obtaining the element selector when a div is being dynamically loaded during an AJAX call

When running two ajax calls, I encounter an issue where the second call loads some HTML onto the page that is needed for processing a specific div in the first call. However, since the div is not present until after the second call is completed, I receiv ...

I'm encountering a npm error on Windows_NT 10.0.19042, does anyone know how to troubleshoot this issue?

After downgrading to [email protected], I encountered an error message that keeps popping up whenever I try to update npm or install new packages. What steps can I take to resolve this issue? npm ERR! Windows_NT 10.0.19042 npm ERR! argv "C:\ ...

Encountering a "Error 404: Page Not Found" message when trying to request a json object from a node server

Working on a RESTful API, I have set it up to run on node.js using express.js, mongodb with mongoose for object modeling, and body-parser for passing HTTP data. However, whenever I start the server and try to access the specified IP address, I encounter a ...

selecting arrays within arrays according to their date values

With an array of 273 arrays, each containing data about a regular season NFL football game, I am looking to categorize the games by week. In total, there are 17 weeks in the NFL season that I want to represent using separate arrays. The format of my array ...

Compare the versions of React used in the linked library and the workspace application

As I work on developing a React library containing my commonly used components, I have organized my project structure in the following way: In the root folder, there is my rollup config file and the src/ folder which houses my library. Upon building, the ...

What is the best way to successfully send an object through AJAX once all its updates are completed?

I am experiencing an issue with my JavaScript code within an event: var userData = tableWidget.grid('userData'); console.log(tableWidget.grid('userData')); $.ajax({ "url": "../../server/query.aspx?tableEvent=reordercolumns&tabl ...

I keep receiving the same error (ENOENT) for all npm commands

Currently, I am running windows 8.1 x64 with all the latest updates installed. I encountered an error while using nodejs version 8.9.1 when running the command "npm -v". As a result, I decided to uninstall this version and switch to version 8.9.3. However ...

Is it possible to extract a specific value from JSON data by making an AJAX call or applying a filter to the fetched JSON data?

I have been utilizing a treeview template and successfully displaying all the data. However, I am facing an issue where I need to pass a value from index.php to getdata.php. I attempted using an AJAX filter on the index.php page and also tried sending a v ...

Is there a specific explanation as to why ng-repeat-start is not functioning properly even with the most recent version of AngularJS?

Can someone please explain why ng-repeat-start is not functioning properly despite using the most up-to-date AngularJS version? I have included it from the CDN: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></scr ...

Having trouble triggering a click event on Ant Design menu button using jest and enzyme

Troubleshooting the simulation of a click event on the Menu component using Antd v4.3.1 Component: import React from 'react' import PropTypes from 'prop-types' import { Menu } from 'antd' import { SMALL_ICONS, PATHS } fro ...