Adding a class to individual elements generated through a v-for loop: a step-by-step guide

I have been working on a basic inventory "checker" that generates 14 divs labeled as either "active" or "inactive". Using Vue, I am able to create these divs with a simple v-for loop:

<div class="inventory">
 <div class="item" v-for="index in 14" :key="index"></div>
</div>

However, I encounter a challenge when receiving data from an external source that provides an array of numbers representing the active inventory items.

For example:

[{"id": "5","date": "2021-10-08 11:30:55"},{"id": "4","date": "2021-10-08 11:30:54"}]

Please note: the date information is not relevant to my query, but it gives insight into the structure of the object. There is additional unnecessary data within it.

In this scenario, I need to assign an "active" class to the 4th and 5th item in my inventory based on the provided data. I am unsure how to iterate through the v-for looped items to conditionally add the 'active' class if the inventory id matches the supplied id. Any suggestions or handy Vue tricks that could assist me here? Feel free to reach out if anything needs clarifying!

Answer №1

If you wish to transform the array from another source into one that consists of IDs, consider the following approach:

let otherSource = [{"id": "5","date": "2021-10-08 11:30:55"},{"id": "4","date": "2021-10-08 11:30:54"}]
// Store active IDs as a state/data
this.activeIds = otherSource.map(el => Number(el.id))
// Define activeIds as a computed property
activeIds(){
   return otherSource.map(el => Number(el.id))
}

You can assign activeIds to a state or computed property.

Next step would be:

<div class="inventory">
  <div class="item" v-for="index in 14" :class="activeIds.includes(index) ? 'active' : 'inactive'" :key="index" ></div>
</div>

To enhance this further, consider transforming the last snippet into a computed property like so:

activeIds.includes(index) ? 'active' : 'inactive'

This should sufficiently address your requirements.

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

Learn how to display two different videos in a single HTML5 video player

Seeking a solution to play two different videos in one video element, I have found that only the first source plays. Is jQuery the answer for this problem? HTML Code: <video autoplay loop id="bbgVid"> <source src="style/mpVideos/mpv1.mp4" type ...

Extracting dynamic content from a webpage using Selenium with Javascript rendering capabilities

Seeking a way to extract data that populates the SVG elements on a specific page: The page seems to be driven by JavaScript, making traditional BeautifulSoup methods in Python ineffective. After inspecting the network for XHR requests, it doesn't see ...

Leveraging React Native to retrieve information from a promise in JSON format

After successfully fetching the JSON data, I now have an array. My question is how can I utilize the elements within this array in a React Native environment? Below is my current approach: export default function display() { const fetching = async() => ...

`Achieving object placement on top of another object in ThreeJS`

Being new to ThreeJS, I am seeking help with a basic question. I have loaded multiple GLTF files into my scene and I need to position one object on top of another (but the position should be adjustable later on) For instance: https://i.sstatic.net/oJq1BIi ...

Emphasize today's date on the w3widgets adaptable calendar

While developing a website featuring a calendar to showcase events, I came across w3widgets, which proved to be quite helpful. However, I encountered an issue when trying to highlight the current date on the calendar. It seems that the calendar only highli ...

javascript display hide choose among

I am attempting to display another set of options when the user selects a specific item. For example, if the user selects "Products," then a new selection box should appear with different product types. See my code below: <html> <head> <m ...

The contact form displays a confirmation message indicating successful submission, however, it fails to actually send the email

Having issues with a PHP script I created for the contact page on my website. After a user fills out and submits the form, they see a success message but the email is not sent. Can someone review this script and point out where I went wrong? <?php ...

Is it possible to have nullable foreign keys using objectionjs/knex?

It seems like I'm facing a simple issue, but I can't quite figure out what mistake I'm making here. I have a table that displays all the different states: static get jsonSchema() { return { type: 'object', propert ...

Creating a responsive layout that sets the window height to 100% and automatically adjusts sibling divs when the content within parent divs exceeds the defined height

<section> <div class="section-wrap"> <h1>page1</h1> </div> </section> <section> <div class="section-wrap"> <h1>page2</h1> </div> </section> My attempt at impleme ...

Unable to dynamically add an element to a nested array in real-time

I'm currently developing an angular tree structure that contains a large nested array. nodes : public fonts: TreeModel = { value: 'Fonts', children: [ { value: 'Serif - All my children and I are STATIC ¯\ ...

Avoid invoking the throttle function from lodash

I am currently facing an issue in my React project with a throttle function from lodash. The requirement is that the function should not be executed if the length of the parameter value is zero. I have tried checking the length of the value and using thro ...

"Utilizing Express in combination with Vue: A beginner's guide

Just delving into the world of Node js, Express and Vue. I've created a pomodoro timer website using vue (sans vue-app/vue-cli) that I'm eager to deploy on Heroku. The site runs flawlessly on my local machine with Webstorm IDE, but I'm stru ...

What are the steps to resolve the TypeError related to reading 'split' on mongoose when properties are undefined?

Just successfully connected mongoDB with mongoose, but encountered an error stating TypeError: Cannot read properties of undefined (reading 'split'). How can I resolve this issue? Below is the code snippet: export const dbConnect = async () => ...

issue with vue v-on:click, interactions are not functioning

I recently started working with vuejs and I'm attempting to create a javascript shopping cart. However, I have encountered an issue with my method. The output is supposed to be an HTML table with some v-on:click actions that aren't functioning as ...

Unable to establish successful Ajax connection with PHP function

I'm encountering an issue with submitting a form through ajax and I can't seem to figure it out: Ajax - samepage <script type="text/javascript"> $(document).on('submit','.subscribe',function(e) { $.ajax({ url: &apo ...

Issue with material-ui-dropzone, the DropzoneAreaBase component not displaying the preview of the uploaded files

Has anyone encountered issues with the DropzoneAreaBase component from the material-ui-dropzone library? I am having trouble getting it to display added file previews. Any insights into why this might be happening? <DropzoneAreaBase onAdd={(fileObjs) ...

Functionality limited to Firefox browser

I'm having some trouble with my website development in HTML5 and CSS3. Specifically, I am struggling to get my processing sketch to work on browsers other than Firefox. Below is the code I am working with: <!DOCTYPE html> <html> ...

Troubleshooting the unsuccessful outcome of the node js async.map function

Context I am new to working with Node.js and the async module. I am encountering difficulties with making synchronous calls to my redis database. Objective My ultimate goal is to return a JSON object when the user calls my REST API's GET method. Th ...

Overtaking a property in a node_module interface: a guide

I am facing a situation where I need to modify an existing interface property in my custom type declaration file, rather than creating a new one. Despite trying various approaches, such as attempting to omit the property, I have not been successful in ach ...

Struggling with organizing my code in node.js - it's all over the place and not very reliable. How should I tackle this

Can anyone help me troubleshoot an issue I'm facing with code that writes to the console late or in random order? var request = require('request'); var vFind = 'HelloWorld'; var vFound = false; var vSites = ['http://www.youtu ...