What is the best way to create row numbers within a Vue component?

I am working on a project with two Vue components. The first component code looks like this:

<template>
  <div>
    <b-row>
      <div class="pl-2 d-flex">
        <div class="card-body">
          <p class="mb-0 w-5 w-sm-100">Number</p>
          <div class="w-30 w-sm-100">Description</div>
          <div class="w-20 w-sm-100">Date</div>
          <div class="w-10 w-sm-100">Modified By</div>
        </div>
      </div>
    </b-row>

    <b-row key="list">
      <b-colxx xxs="12" class="mb-3" v-for="(item,index) in items" :key="index" :id="item.id">
        <list-item
          :key="item.id"
          :data="item"
          :index="index"
        />
      </b-colxx>
    </b-row>
    ...
        <b-pagination-nav
          ...
        >
        </b-pagination-nav>
    ...
  </div>
</template>
<script>
import ListItem from "./ListItem";
export default {
  components: {
    "list-item": ListItem
  },
};
</script>

The second component, which is the child component, looks like this:

<template>
<b-card no-body>
    <div class="pl-2 d-flex">
        <div class="card-body">
            <p class="mb-0 text-muted w-5">{{index+1}}</p>
            <p class="mb-0 text-muted w-30">{{data.description}}</p>
            <p class="mb-0 text-muted w-20">{{data.date}}</p>
            <p class="mb-0 text-muted w-10">{{data.created_by}}</p>
        </div>
    </div>
</b-card>
</template>

<script>
export default {
    props: ['data', 'index'],
}
</script>

In my first component, I use the index to give row numbers. However, when I move to another page, the line number resets to 1. How can I go about solving this issue? Any help would be greatly appreciated. Thank you.

Answer №1

To add line numbers to your items and loop over it, you can create a computed property in Vue.js:

new Vue({
  el: '#demo',
  data() {
    return {
      items: [],
      fields: [{key: "lineNumber", label: "Number",}, {key: "postId", label: "Post ID",}, {key: "id", label: "ID",}, {key: "name", label: "Name",}, {key: "email", label: "Email",}, {key: "body", label: "Body",},],
      currentPage: 0,
      perPage: 10,
      totalItems: 0,
    }
  },
  computed: {
    itemsWithLineNumber() {
      return this.items.map((item, idx) => {
        return {
          ...item,
          lineNumber: (this.currentPage - 1) * this.perPage + idx + 1,
        };
      });
    },
  },
  methods: {
    async fetchData() {
      await axios
        .get(
          `https://jsonplaceholder.typicode.com/comments?_page=${this.currentPage}&_limit=${this.perPage}`
        )
        .then((res) => {
          this.totalItems = 500;
          this.items = res.data;
        });
    },
    changePage(nr) {
      this.pageNr = nr
    }
  },
  watch: {
    currentPage: {
      handler: function (value) {
        this.fetchData().catch((error) => {
          console.error(error);
        });
      },
    },
  },
  async mounted() {
    await this.fetchData()
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<script src="https://polyfill.io/v3/polyfill.min.js?features=es2015%2CIntersectionObserver" crossorigin="anonymous"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg+GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="demo">
  <div>
    <b-table
      show-empty
      :items="itemsWithLineNumber"
      :fields="fields"
      :current-page="currentPage"
      :per-page="0"
    ></b-table>
    <b-pagination
      size="md"
      :total-rows="totalItems"
      v-model="currentPage"
      :per-page="perPage"
    ></b-pagination>
  </div>
</div>

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

Understanding the reverse order of numbers displayed with while loop and innerHTML

function doItAgain() { var loopCount = 5; while(loopCount > 0) { var target = document.getElementById("target"); target.innerHTML = "LoopCount: " + loopCount + "& ...

Troubleshooting Challenges with JSON and jQuery Encoding

Having an issue with displaying data from a JSON file using jQuery: { "nombre": "Jesús Ramírez", "edad": "25 Años", "imagen":"file.jpg" } Here's my code: JAVASCRIPT $.getJSON(file.json, function(data) { var name= data.nombre; ...

Utilizing jquery to showcase the information in a neat and organized table

Having an input text box and a button, I am looking to display dummy data in a table when any number is entered into the input field and the button is clicked. Here is what I have tried: My Approach $("button#submitid").click(function () { $(&quo ...

What are the benefits of installing both libraries A (react-router) and B (react-router-dom) together, especially when library B relies on library A for functionality

I am currently exploring the necessity of explicitly specifying all dependencies in the packages.json file. For instance, when I want to utilize the react-router library. According to the official documentation: npm install react-router@6 react-router-d ...

What is the best way to redirect a user to a different URL in Express while also sending additional data along with the request

[NODE, express] Developing a Facebook application where user grants access and is redirected to my site with a unique code at abc.com/heyBuddy/fb/callback?code="adasdasdasda". Once the code is received in route router.get('/heyBuddy/fb/callback', ...

Update the JavaScript and CSS files following an AJAX request with $.get

I am encountering an issue where my global CSS and JS files contain all the necessary definitions, but when I load new HTML blocks via AJAX $.get, these new elements do not receive the correct CSS/JS definitions. Is there a convenient way to refresh the ...

Is it possible for me to create a Pomodoro clock similar to this one?

Can you provide guidance on creating a Pomodoro clock similar to this design: https://i.sstatic.net/qhd1Z.png As time progresses, the arrow should move around causing the circumference of the circle to increase. What approach or library would you recomm ...

What is the correct method for exporting an ES6 module function as a library to be utilized in a Node.js application?

Imagine having a node.js application that does not pass through webpack bundling: Node App const Html = require('./build/ssr-bundle.js'); let result = Html.ssrbundle.render(); console.log(result); Here is my ES6/JSX file, which undergoes web ...

React in 2022 has encountered an unexpected expression when it was expecting either an assignment or function call

I am having difficulty updating a chart with values received from an API. I am unsure about how to adjust the useEffect hook in my code. Any advice would be greatly appreciated. Here is a snippet of my code: import React, { useEffect, useState } from &quo ...

Steps for generating a fresh type denotation from a value within an object

Is it possible to create a new type alias based on an object's values? const test = { 'a': ['music','bbq','shopping'], 'b': ['move','work'] }; How can we extract this information f ...

Tips for converting a parent class Sprite into a subclass MySprite in Cocos2d-JS

There is a custom class called MySprite that extends Sprite and includes additional methods. var MySprite = cc.Sprite.extend({ ctor:function(){ this._super(); }, doSomethingStrange:function(){ //meow meow } } ); In the game s ...

In a Javascript scenario, only the initial button can successfully submit to an Ajax form even when having unique

Similar issues have been reported by other users when looping rows of buttons, often due to inadvertently reusing the same Id or value. I am facing a similar issue, but each of my buttons is unique. AJAX request <script> $(document ...

Encountering errors during the installation of packages using npm

Can someone please assist me with fixing these errors? I am a beginner in the world of web development and encountered this issue while working with react.js and setting up lite-server. Any guidance on how to resolve it would be greatly appreciated. ...

How can an event be initiated from within the Created method?

Is there a way to retrieve the value of a GET parameter and then trigger an event from within the Created method? I attempted the following approach, but the click method could not be found: created(){ if(this.$route.query.text!=''){ ...

Ways to emphasize an HTML element when clicked with the mouse

Can JavaScript be used to create code that highlights the borders of the HTML element where the mouse pointer is placed or clicked, similar to Firebug, but without needing a browser extension and solely relying on JavaScript? If this is possible, how can ...

Combining several files into a single variable to encode

I'm encountering an issue with the multiple file upload option. Even though it shows that 2 files have been uploaded, when I try to print the encoded value in the console, it only encodes and takes the value of my last uploaded file. How can I encode ...

Open a Link in the Default Browser with a Right Click in node-webkit

I'm using an iframe in my node-webkit app. I want users to have the ability to right-click on links within the iframe (a tags) and choose an option like "Open in Browser" to open the link in their default browser. Can this be done? ...

Create an excel spreadsheet using HTML tables with the help of jQuery

Upon clicking a button, I aim to generate an excel sheet. Essentially, I am trying to achieve what is being discussed here (Kalle H. Väravas answer). If the following links are not working within Mozilla browser, then maybe my code requires ActiveXObject ...

What is the purpose of using route('next') within ExpressJS?

In the documentation it states: You can have multiple callback functions that act as middleware and can invoke next('route') to skip the remaining route callbacks. This is useful for setting pre-conditions on a route and then passing control t ...

What is the best way to manage a batch of files in a response from an Ajax POST request?

Currently, I am utilizing the OGRE web client to convert GeoJSON text data into ESRI shapefiles by making a POST request with Ajax. var data = { "type": "FeatureCollection", "features": [{ "type": "Feature", "geometry": { "type": "Point", "coord ...