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

"Encountering problems with location search function on Instagram API for retrieving posts

I've been working on integrating two APIs – Instagram and Google Maps. While I've managed to get everything functioning smoothly, there's an issue with displaying "up to 20 pictures" around a specific location. I'm unsure why this in ...

Using an xmlhttprequest to retrieve a PDF file functions properly in synchronous mode, but encounters issues in

Today I'm experimenting with some code that scrapes PDFs from a chrome extension by detecting user-clicked links. I've noticed that synchronous xmlhttprequests work perfectly for both HTML documents and PDFs. However, I seem to be facing an issue ...

Can you offer advice on creating jasmine tests for an Angular controller and service similar to this?

I've been struggling with this issue for hours, mainly because I'm still new to Jasmine and AngularJS. The problem lies within my controller. angular.module('toadlane.controllers', []). controller('MainController', functi ...

Angular2: the setTimeout function is executed just a single time

Currently, I am working on implementing a feature in Angular2 that relies on the use of setTimeout. This is a snippet of my code: public ngAfterViewInit(): void { this.authenticate_loop(); } private authenticate_loop() { setTimeout (() =& ...

Navigating through the Express.js routes incorrectly

I currently have 3 different express.js routes set up: app.get('/packages/:name', (req, res) => {...}); app.get('/packages/search/', (req, res) => {...}); app.get('/packages/search/:name', (req, res) => {...}); At t ...

Selenium Python not generating event when clicking on element (Key event missing from datafile)

One issue I am facing is that clicking on a button element does not trigger the event. Specifically, while attempting to add an item to the cart, a size must be selected before clicking the "add to cart" button. This problem occurs when using the Chrome he ...

When utilizing a Service through UserManager, the User variable may become null

Utilizing Angular 7 along with the OIDC-Client library, I have constructed an AuthService that provides access to several UserManager methods. Interestingly, when I trigger the signInRedirectCallback function from the AuthService, the user object appears ...

Is JSONP functioning properly in Chrome but not in Firefox or Internet Explorer?

I'm currently in the process of developing a mobile site and I've opted to use JSONP requests via jQuery to communicate with the data server in order to retrieve information for display on the mobile site. The advice given to me was to avoid usin ...

Programmatically Expand and Collapse All nodes in MUI DataGrid using ReactJS

Is there a way to programmatically expand or collapse all rows in MUI ReactJS DataGrid? What have I tried? I attempted to use the defaultGroupingExpansionDepth property as suggested in the MUI documentation: export const EXPAND_ALL = -1; export const COLL ...

Using relative positioning in CSS causes the div to move to a new line

Feel free to check out this demo I've created for reference: http://jsfiddle.net/jcb9xm44/ In a nutshell, the scenario involves two inline-block divs nested within a parent div: <div class="outer"> <div class="inner1"> Y & ...

Command for controlling volume in DiscordJS

Despite my efforts, I am struggling to write a command that successfully changes the volume of the music being played. Every time the player and resource variables in the volume() function are empty while the bot is playing the song. What can I do to resol ...

Dynamic height adjustment for Bootstrap right column

I am struggling to create a layout with a right column using bootstrap. I can't figure out how to achieve the desired arrangement shown in this image. https://i.stack.imgur.com/VaIWD.png I have attempted various methods but the right column does not ...

Capable of generating a string-keyed map that results in an "Unexpected number error" when the key is referenced

Take a look at the following code snippet: var arr = [{"id":"123", "name":"Jyotirmoy"}]; var mapObj = {}; for(var i=0; i < arr.length; i++){mapObj[arr[i].id] = arr[i];} After creating the map, attempting to access it using the key 'mapObj.123&ap ...

Ways to prevent decreasing the value below zero in ReactJS?

I have created two buttons, one for increasing and another for decreasing a counter value. However, when I click on the minus button, it should not display negative values. But in my case, when I click on the minus button (initially at zero), it shows -1, ...

VueJS failing to pass parent data to child component

I'm fairly new to Vue Framework and I'm trying to figure out how to update a child component based on changes in the parent component's attributes. In the code snippet below, I've created a component that displays a greeting message bas ...

When trying to access document.cookie, an empty string is returned despite the presence of cookies listed in developer tools, and the httpOnly flag is set

There are times when I encounter an empty string while trying to access document.cookie on the login page, despite the following conditions being met: The cookies are visible in the Chrome and Firefox developer tools, The httpOnly flag of the cookie I&ap ...

Does the Error page in Next JS 13 fail to properly manage fetch API errors?

After referencing the documentation for Next.js with app router, I followed the instructions to create an error.tsx page within my app folder (app/[lang]/error.tsx). This file contains the code provided in the docs. Additionally, I included some API calls ...

What is the process for obtaining a client-side cookie using next.js?

I'm currently facing an issue where I can't seem to maintain a constant value for the isAuthenticated variable between server-side and client-side in next.js. In my setup, I am using a custom app.js file to wrap the app with Apollo Provider. The ...

What is the process for activating and deactivating the scroll trigger within Material UI's useScrollTrigger module?

I'm currently working on setting up a survey page with Material UI in React. My goal is to have the survey questions appear when the user scrolls over them and disappear when they scroll out of view, similar to the behavior on this page. After some r ...

The CSS transition will only activate when coupled with a `setTimeout` function

After using JavaScript to adjust the opacity of an element from 0 to 1, I expected it to instantly disappear and then slowly fade back in. However, nothing seems to happen as anticipated. Interestingly, if I insert a setTimeout function before applying th ...