Encountering a problem with Tailwind dynamic grid in Vue3

Greetings fellow Stack Overflow members!
I am currently working on a project using Vue3 + tailwindcss.

My goal is to create a dynamic grid layout similar to the following:

Corrrection: Here, I am aiming for a repetitive layout with dynamic loop items

Below is the snippet of my code:

<template>
  <div class="min-h-screen flex items-center bg-purple-500">
  <div class="flex-1 max-w-4xl mx-auto p-8">
    <ul class="grid grid-cols-12 gap-8">
      <template v-for="(i,index) in 8" :key="index">
       <li
          class="col-span-12 sm:col-span-6 md:col-span-4  bg-white rounded-lg shadow-xl"
           v-if="updateCounter(index) || (index+1) % 8 != 0"
        >
          <div class="h-24"> {{ index }} {{updateCounter(index) }}</div>
       </li>
        <li
         v-else
          class="col-span-12 sm:col-span-6 md:col-span-6 bg-white rounded-lg shadow-xl"
         >
          <div class="h-24">{{ index }}  </div>
       </li>
      </template>

    </ul>
  </div>
</div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

const count = ref<number>(2)
const checkForCols = ref<boolean>(false);
const total = ref<number>(6)

const updateCounter = (index: any) => {
  if( total.value == index ){
    total.value = total.value + 6 + count.value
    return true
  } else {
    return false
  }
}
</script>

Unfortunately, my output is not as expected.

I have already dedicated 2 days to solving this issue, but to no avail.
Can anyone provide some guidance on how to achieve the desired outcome?

Thank you in advance for your assistance.

Answer №1

Your solution becomes more complex because you are changing the state while calculating the layout within the v-for loop. Avoid this practice!

Modifying the state triggers recalculation of everything that relies on that reactive state, including items that have already been iterated through. This is considered an anti-pattern for several reasons:

  • It often causes performance problems due to changes triggering endless loops
  • It can be challenging to track the mutations when debugging, leading to difficulties for yourself and others

The fact that you had to ask a question about it proves the point. If you had refrained from modifying the state inside the loop, you might have figured out the function below on your own.


What you should aim for:

  • Utilize the count
  • Create a function that correctly returns md:col-span-${x} for the last items based on count and index. Here's an example:
const count = ref(8)
const getMdClass = (index) => {
  const rest = count.value % 3;
  if (index > count.value - rest - 1) {
    return `md:col-span-${12 / rest}`;
  }
  return "md:col-span-4";
}

This function typically returns md:col-span-4, except in the following cases:

  • md:col-span-6 for the last 2 items when the count is in the form of (3 x n) + 2,
  • md:col-span-12 for the last item when the count is in the form of (3 x n) + 1.

Check out this demonstration (typescript and <script setup> are not used, but the logic is intact). I turned count into a prop for interaction purposes.

Important: The function is slightly adjusted in the sandbox due to my use of v-for="n in count", which starts from 1 rather than 0.

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

Master the Art of Crafting Unique URLs

I am developing a web page that requires me to call two queries, each requiring an ID. However, I'm unsure of the best way to pass these IDs in the URL. For instance, one query is for books and the other is for authors. Currently, I have considered tw ...

The error message "element is not defined" is indicating an issue related to the cordova-plugin-google

In my current project using Ionic 3, I decided to implement map-related features by incorporating the Google Maps plugin recommended by the Ionic Team. This specific plugin serves as a wrapper around cordova-plugin-googlemaps. Following the steps outlined ...

Applying a CSS style to a division element

Can I modify the style attribute of a div element using JavaScript? <div style="color:#0000FF"> <h3>This is a heading</h3> <p>This is a paragraph.</p> </div> I am interested in achieving the following: Changing th ...

Initiating an Ajax POST request by clicking a button

I have a button on my webpage that, when clicked, currently prints the value of an element to the console using a basic function. Instead of just printing the value, I want to update my Django view by sending it through a POST request. Here's the cu ...

Exploring the concept of sharing variables between files in Node.js and JavaScript

I have a situation where I am working with files that require database access. One of the files contains code like this: ... var dynamo = new AWS.DynamoDB.DocumentClient(); module.exports.getDatabase= function(){ return dynamo; }; ... I'm curiou ...

Using Angular, we can assign an array iteration as the value for a dropdown option in

Following the controller logic: $scope.form_data = { day: 'Day' }; $scope.days = [ 'Day',1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20, 21,22,23,24,25,26,27,28,29,30, 31 ]; In the html section: <select n ...

Are trailing commas or missing keys acceptable in JavaScript object notation?

I have created a code generator and I am contemplating whether or not to address the issue of the extra comma at the end. While Internet Explorer seems to ignore it, I want to ensure cross-browser compatibility and generate valid code. function init() { v ...

What is the best way to show JSON array data in jQuery without using double quotes?

I have encountered an issue where I need to remove the double quotes from my json_encode output. To achieve this, I have used the following code: $json_string = json_encode($data); $json_string = str_replace('"','',$json_string); echo ...

Bringing in a JavaScript file into a Svelte component

Today, I stumbled upon Svelte and I am really intrigued by the concept. However, I encountered an issue while attempting to import a small helper.js file. No matter what I try, whenever I reference the class, I receive the error: ReferenceError: Helper ...

Steps for navigating to a different page by clicking on a gridview row

Currently, I am utilizing a grid view on my webpage. My specific request is that upon clicking on any row within the grid, it should redirect to a separate page where all the details of the selected row will be displayed. Appreciate your assistance! ...

What is the best way to send multiple arrays of JSON objects to a Stimulsoft report using JavaScript?

I am currently working with this JavaScript code snippet: var viewer = new window.Stimulsoft.Viewer.StiViewer( null, "StiViewer", false ); var report = new window.Stimulsoft.Report.StiReport(); const { data: reportData } = await GetRequest ...

Tips for avoiding the default rendering of Nuxt 3 layout?

After reviewing the Nuxt 3 documentation and finding it lacking in explanation, I turned to the Nuxt 2 docs. According to them, the default layout should be replaced by a specific layout specified within the name property of the <nuxt-layout> compone ...

I am experiencing an issue where the position of the value in the returned response array keeps changing after an Ajax request is made. How can

I am currently using a script that sends an array of numbers through Ajax to a web server. These numbers are then used to query a database, and the corresponding values from the table are sent back. I then display these values in respective divs within my ...

Demonstrate the utilization of JQuery to unveil a secondary menu

I need assistance in implementing a sub-menu that automatically appears within 2 seconds after the page loads, instead of requiring user interaction. I am currently utilizing JQuery, which serves as the core framework for my website. It is crucial for this ...

The jQuery click and load function are failing to function as expected

Currently, I am facing an issue while trying to load text from a txt document into a div using the following code: $(document).ready(function(){ $('button').click(function(){ $('#contenthere').load('Load.txt'); ...

What is the secret behind Node.js's ability to efficiently manage multiple requests using just one thread

After conducting some research on the topic, I noticed that most people tend to focus solely on Non-blocking IO. For instance, if we consider a basic application that simply responds with "Hello World" text to the client, there will still be some executio ...

Experience the dynamic bouncing marker feature in Next.js React-Leaflet with the powerful tool Leaflet.SmoothMarkerB

I'm a beginner in front-end development and I'm attempting to create a bouncing marker in React-leaflet using the leaflet.smooth_marker_bouncing plugin version 1.3.0 available at this link. Unfortunately, I couldn't find enough documentation ...

unable to connect css file to document

My index.html file is not reading the style.css file for some reason, even though it is linked. I have added the type and checked the path, but still facing issues. Can anyone help troubleshoot this problem? Thank you. https://i.sstatic.net/xxpBV.png htt ...

What is the process for updating JSON using TextFields?

I am currently facing an issue with my TextFields displayed within a material-ui dialog. These TextFields are initially populated by JSON data, which you can see in the example below. The problem is that once the TextFields are populated, I am unable to up ...

Numerals for Central Leaflet Marker

Is there a way to effectively center numbers inside markers? Here is the current situation: View Marker with Number How to Create a Marker return L.divIcon({ className: "green-icon", iconSize: [25, 41], iconAnchor: [10, 44], popupAn ...