What's the best way to retrieve the quantity of each item through v-for in Vue?

In my Vue code snippet below:

var itembox = new Vue({
    el: '#itembox',
    data: {
        items: {
            cookiesncreme: {
                name: "Cookies N Cream",
                description: "description"
            },
            chocolateswirl: {
                name: "Chocolate Swirl",
                description: "description"
            },
            peanutbutter: {
                name: "Peanut Butter",
                description: "description"
            }
        }
    }
});

And here is the corresponding HTML code:

<div id="itembox">
    <div v-for="(item, index) in items">{{ index }} - "{{ item.name }}"</div>
</div>

I am aiming to display the items in a numbered list format, like shown below:

<div>1 - Cookies N Creme</div>
<div>2 - Chocolate Swirl</div>
<div>3 - Peanut Butter</div>

However, the current output displays the items with their keys instead of numbers, as seen here:

<div>cookiesncreme - Cookies N Creme</div>
<div>chocolateswirl - Chocolate Swirl</div>
<div>peanutbutter - Peanut Butter</div>

Do you have any suggestions for achieving a numbered count for each item? Thank you in advance!

Answer №1

If you're working with Vue.js, there's an additional parameter you can pass in certain cases. For instance, consider the following example:

<div id="itembox">
    <div v-for="(item, index, i) in items">{{ i+1 }} - {{ index }} - "{{ item.name }}"</div>
</div>

Take note of how the i parameter is used, representing the index number. I've put together a functioning Fiddle showcasing this here. To delve deeper into Vue.js, feel free to explore my Vue.js training course. If you found this answer helpful, consider marking it as accepted and giving it a thumbs up.

Answer №2

As per the Vue documentation found here

In another approach, it is possible to define an alias for the index (or key if being used on an Object):

<div v-for="(item, index) in items"></div>
<div v-for="(val, key) in object"></div>
<div v-for="(val, key, index) in object"></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

Utilizing React Native to Query, Filter, and Save a Single Document Field Value from Firestore Database into a Variable/Constant

My current task involves setting up a Firebase Firestore Database in order to filter it based on a specific field value within a document. The collection I am working with is named "PRD" and consists of thousands of documents, each sharing the same set of ...

A detailed guide on sending Joomla form information to a controller function using Ajax communication

Within my Joomla 3.3 form, I have integrated an ajax script aimed at dynamically updating some form fields. The core of the script looks like this: formdata = new FormData(); jQuery.ajax({ type: "POST", dataType: "json", timeout: 6000, url: "index.php?opt ...

Cease the loading of a script in an HTML file

I have encountered a challenge in preventing a script from loading on my Wordpress website. The HTML file contains two scripts: <script type="0f1a6d7ca503db410c0d10c4-text/javascript" src='https://www.[-----------].se/wp-content/plugins/ ...

Exploring the assortment of reactions post-awaitReaction in node.js

The current code runs smoothly, but I encounter an issue when attempting to send messages after selecting either the X or check option. Instead of the expected outcome, I receive Despite my understanding that this collection is a map, all attempts to acce ...

Challenge encountered in posting a variable generated through ajax

Embarking on my first attempt at utilizing ajax has been quite challenging. Essentially, when an option is selected from the initial field, javascript and xml trigger a php script that generates the next dropdown menu based on information fetched from an S ...

Storing information in a Database using AngularJS and PHP

Seeking assistance with connecting Angular to a PHP database. I have successfully retrieved data in my Angular setup, but struggling to save it to the database. Here's the HTML code I'm using: <form ng-controller="AppCtrl" name="add_user"> ...

inquiry on php function properties

I have a PHP file containing two functions. <?php function first () { //in real case more conditions echo "first"; return true; } function second () { //in real case more conditions echo "second"; return true; } first(); second(); ?> And in an ...

Implementing a function to save a file to a nested directory in node.js

Currently, I'm utilizing node and express with the following directory structure: public img css js server.js Within server.js, I have the code snippet below for writing to a png file: fs.writeFile('testfile.png', imageData, func ...

Verify in JavaScript if the script is executing within a WinStore (WinJS) program

I am in the process of developing a JavaScript library that is compatible with both Windows Store (WinJS) applications and traditional HTML/JavaScript apps. The dependency I am utilizing loads dynamically and has separate SDKs for WinJS apps and standard w ...

React is unable to properly utilize Mui icons in a basic Card example

C:\Users\Yeap\Documents\react sitio web\my-app\node_modules\react-scripts\scripts\start.js:19 throw err; ^ [Error: ENOENT: no such file or directory, stat 'C:\Users\All Users'] { errno ...

What is the process of removing a document with Next.JS and MongoDB by utilizing next-connect?

Currently in the process of constructing my first CRUD application using NextJS/Mongodb and I've decided to utilize next-connect for handling the methods. As a newcomer to this field, I have managed to successfully create posts and update user profile ...

Uncover the content of a base64 encoded string and convert it into

A JSON response has been linked on the user's request to retrieve an excel document. The structure of the response is as follows: { "format": // file extn ----only xls "docTitle": //file name "document" :// base 64 encoded data } The attem ...

Global registration of single file components is necessary to utilize them across

I need some help with VueJS. I am trying to create a registration form, but I am encountering an error when registering the component globally. This is all new to me, so any assistance would be greatly appreciated. Here is the specific error message that ...

There seems to be an issue with connecting to the local server at https://localhost:3000/socket.io/ while using a

I am currently working on a Node.js project where I have a client.js for client-side code, and a server.js on a remote server using sockets to communicate over port 3000 In addition, Apache is running on port 80, with a ProxyPass configuration in place to ...

Ways to adjust the size or customize the appearance of a particular text in an option

I needed to adjust the font size of specific text within an option tag in my code snippet below. <select> <?php foreach($dataholder as $key=>$value): ?> <option value='<?php echo $value; ?>' ><?php echo ...

Once the data is retrieved and the old image is deleted, attempting to upload the new image still results in the old image being displayed in the Next.js application with React Query

async function fetchTour() { const response = await api.get(`/tour/${router.query.slug}`); return response.data; } const { data: tourData, isLoading, isFetching, isTourError: isError, } = useQuery(['fetchTour', router.que ...

Utilizing JavaScript to access and present results from a PHP file located on a separate server

UPDATE I have set the header of my php file as shown below: header("Access-Control-Allow-Origin: *"); Currently, this is the error I am seeing in my browser: "Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Heade ...

Meteor: Transmitting Session data from the client to the server

Below is the code snippet I am utilizing on the client side to establish the Session variable: Template.download.events({ 'click button': function() { var clientid=Random.id(); UserSession.set("songsearcher", clientid); ...

Troubleshooting: Issues with Ajax loading page and click functionality in jQuery

Why won't my ajax function properly? Here are the details of my pages. I am using JQuery to monitor click events and implement ajax for loading the responder page. Can you spot any issues in this code snippet? index.php <html> <head ...

When Socket.emit is called, it outputs <span> elements within a well-structured message

Currently working on a small chat application using Node.js, Express.js, and Socket.IO. However, I'm encountering an issue with formatting. Instead of displaying the message content within <span> tags as intended, it is printing out the actual t ...