The div is not displaying the conditional styling as expected

I need help with mapping an array of cards wrapped in a div. I want the first, second, second-to-last, and last divs to go on a new line or take up the entire row. My project is in Vue3 and I'm using the PrimeVue component library.

<div class="row" v-for="(task, index) in tasks" :class="{ 
    'p-col-12 dp-block': index === 0,
    'p-col-12 dp-block': index === 1,
    'p-col-12': index == tasks.length-2,
    'p-col-12': index === tasks.length-1,
     }" :key="task">
        <Card style="width: 25em; vertical-align: middle;">
            // card content
        </Card>
</div>

In this code snippet, I am assigning the "p-col-12" class based on the index of each item in my array. If the index is 0, 1, tasks.length-1, or tasks.length-2, the class should be applied.

However, I noticed that the second-to-last element is missing the class in the output.

While my conditional styling logic seems correct, I would appreciate feedback from more experienced developers.

Answer №1

To handle this situation, I recommend utilizing a specific method in your code.

methods: {
  getStyleClasses() {
    let className = ''
    if (
      this.index === this.tasks.length - 2 ||
      this.index === this.tasks.length - 1
    )
      className = className.concat(' p-col-12')
    if (this.index === 0 || this.index === 1)
      className = className.concat(' dp-block')
    return className
  },
},

You can implement the method as shown:

<div
  class="row"
  v-for="(task, index) in tasks"
  :class="getStyleClasses()"
  :key="task"
>
  <Card style="width: 25em; vertical-align: middle;">
        // card content
  </Card>
</div>

Answer №2

To style those specific elements using only CSS, you can use the :nth-child and :nth-last-child selectors to make them 100% wide, eliminating the need for unnecessary logic.

For example:

section {
  display: flex;
  flex-flow: row wrap;
  gap: 10px;  
}

div {
  background: yellowgreen;
  height: 100px;
  flex: 1 1 auto;
}

div:is(:nth-child(1), 
       :nth-child(2), 
       :nth-last-child(1), 
       :nth-last-child(2)) {
   flex-basis: 100%;
}
<section>
  <div class="row">1</div>
  <div class="row">2</div>
  <div class="row">3</div>
  <div class="row">4</div>
  <div class="row">5</div>
  <div class="row">6</div>
  <div class="row">7</div>
  <div class="row">8</div>
  <div class="row">9</div>
</section>

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

Troubleshooting Event.target Problem in Firefox 6

When working in Firefox 6, I encountered an issue while trying to identify the target element on which the event occurred. Instead of displaying the desired element, it was showing as undefined in the alert message. Utilizing the Firebug tool for debugging ...

How come my reducer isn't changing the state of my store with ImmutableJS?

I have the following code within my reducer: const copy_states = fromJS(state); const i_copy_jobs = copy_states.get('calendar_jobs').get(s_from_day_key).get(s_dept_id).get(s_job_id); let i_calend ...

multiple urls causing duplication of states in angular ui routes

Currently, I am faced with an issue while using angularjs in combination with angular ui routes. The problem arises when dealing with multiple URLs for a single route. I have a state named "bookDetails" which corresponds to a book that has a unique id an ...

How do I apply a xPage page style using the styleClass attribute instead of directly using the style attribute

Would like to know how to change the background color of an entire page using styleClass instead of directly in the xp:view tag? Here's an example that works: <xp:view xmlns:xp="http://www.ibm.com/xsp/core" style="background-color:#f1f1f1;"> ...

Middleware functions in Mongoose for pre and post actions are not being triggered when attempting to save

After carefully reviewing the documentation, I am still unable to pinpoint the issue. The pre & post middleware functions do not appear to be functioning as expected. I have made sure to update both my node version and all modules. // schema.js const sch ...

steps to extract routing into its own component

Is it possible to extract this routing logic into a separate component? I attempted to use map but it didn't work I want to have only a single route, and change the 'path' when a specific link is clicked const Home = ({ code }) => { re ...

How does the object scope receive, process, and prepare the update for display within the AngularJs view?

AngularJS allows for data-binding to easily display immediate data in our View. This is made possible by the object scope, which acts as a connector between the Logic Code and The View. Additionally, AngularJs supports two-way binding. My question is: H ...

Troubleshooting problem with spacing on three horizontal divs

I am currently working on building an E-commerce website to gain some practice. Here is how the div is set up: .small-container { max-width: 1080px; margin: 5px; padding-left: 25px; padding-right: 25px; } .col-4 { flex-basis: 25%; padding ...

What is the best method for distributing this array object?

I am faced with the task of spreading the following object: const info = [{ name: 'John', address: 'america', gender: 'Male', job: 'SE' }]; I want to spread this array object and achieve the following format: form:{ ...

Svelte Material UI Circular Progress Indicator encountering issues

I'm having trouble getting the Svelte Material UI Circular Progress indicator to function properly. I attempted to implement it in my project initially, and then decided to try it out in Code Sandbox using the provided code from the documentation. How ...

Issues arose when attempting to navigate in a JavaScript handler within ASP.NET MVC

As a newcomer to Javascript, I hope my question isn't too basic. I have a button in my ASP.NET MVC 4 view: <input name="button" type="button" id="button1" value="Click me1"/> In order to create a click handler for the button, I've added ...

Error in NodeJs: ReferenceError - the variable I created is not defined

Encountering an issue while attempting to use a module in my router file. I have successfully required it, but now I am seeing the following error message: ReferenceError: USERS is not defined at c:\work\nodejs\router\main.js:32 ...

Guide on extracting faulty image links using JavaScript and transferring them to PHP

I have a website that showcases numerous external images and thumbnails, often exceeding 100 on a single page. These image URLs are crawled, indexed, stored in a MySQL database, and later displayed using a simple loop code from queries. <img src="<? ...

Effortless link to a Gremlin database using a JavaScript app

I apologize for my lack of technical knowledge, but I am struggling to solve this issue despite studying the documentation. My goal is to establish a connection with a standard Gremlin DB (Cosmos) using gremlin. While it works well from the server, encoun ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

Enforce the retrieval of all fields, even those that have been overridden

I have a query that utilizes mongoose and involves a select operation. The model's schema is configured to exclude two specific fields, like so: contents: { type: String select: false }, password: { type: String select: false } Howev ...

Retrieve pixel information upon touch in an Appcelerator Titanium application on Android or iPhone

Can pixel level data of an image view be accessed using Titanium Mobile on Android/iPhone? ...

The Failure of window.pushState in HTML 5 History

Looking to implement ajax loading for updating center content and URL without refreshing the page. Everything seems to be working fine except for the history management. It appears that window.pushState is not properly recording URLs or the popstate even ...

The initial setTimeout function functions correctly, however the subsequent ones do not operate as expected

I have developed the following code: bot.on('message', message=> { if(message.content === "come here") { message.channel.send('hey'); setTimeout(() => { message.channel.send('i am here' ...

A guide to accessing REST services in AngularJS using basic authentication

I currently have a REST service up and running on my server. Using Chrome Postman, I am able to access this service with Basic Authentication. However, I now want to build a user interface in AngularJS to display the data received from the REST service. T ...