A helpful tip for creating line breaks within a Vue JS v-for loop using CSS

I am looking to arrange the names in alphabetical order when a list item is clicked. My tools of choice are Vue.js and Flex Grid.

The list item I am working with is called ListAll,

When clicking on ListAll, I want to display all the records grouped by names from the nameList array. However, I am encountering difficulties in displaying the grouped names as intended. The problem lies in creating line breaks after each set of names. I am utilizing Flex Grid for this purpose. After displaying the records starting with A, the records starting with B should appear on a new line, but unfortunately they do not break to a new line. How can I implement a line break after each group of names using Vue.js, ES6, or CSS?

To add a line break, I have tried using

<div class="break"></div>
, but it is not achieving the desired outcome.

The records are currently being displayed in 4 columns without any line breaks using flexbox grid CSS class, as shown below:

Apples Apricots Avocados Almond
Abiu Berry Bananas Boysenberries 
Blueberries Breadfruit Carambola Cantaloupe 
Cranberries Cherries Custard-Apple

Expected Output:

Apples Apricots Avocados Almond
Abiu 
Berry Bananas Boysenberries Blueberries 
Breadfruit
Carambola Cantaloupe Cranberries Cherries
Custard-Apple

AlphabeticalFruitsName.vue

<template>
    <div id="wrapper">
        <ul class="listitems">
            <li><a
                href="javascript:;" @click="userSelection('ListAll')">ListAll</a>
            </li>
        </ul>
        <div class="grid-container">
            <div v-for="(name, index) in nameList" :key="name" class="grid-item">
                <ul v-for="letter in alphabets" :key="letter">
                    <li v-if="name.startsWith(letter)"><a>{{ name }}</a></li>
                    <div class="break"></div>
                </ul>
            </div>
        </div>
    </div>
</template>

<script>
export default {
  name: 'AlphabeticalFruitsName',
  data() {
    return {
      nameList: [],
      alphabets: ['A','B','C','D','E','F','G','H','I','J','K','L',
        'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',],
      names: [
        { name: 'Apples' },{ name: 'Apricots' },{ name: 'Avocados' },{ name: 'Apple Berry' },
        { name: 'Apple guava' },{ name: 'Almond' },{ name: 'Almond' },{ name: 'African Honeysuckle' },
        { name: 'African Plum' },{ name: 'Abiu' },{ name: 'Bananas' },{ name: 'Boysenberries' },
        { name: 'Blueberries' }, { name: 'Bing Cherry' },{ name: 'Breadfruit' },{ name: 'Cantaloupe' },
        { name: 'Carambola' },{ name: 'Cherimoya' },{ name: 'Cherries' },{ name: 'Cranberries' },
        { name: 'Custard-Apple' },{ name: 'Dates' }, { name: 'Honeysuckle' },{ name: 'Gooseberries' },
        { name: 'Grapefruit' },{ name: 'Grapes' },{ name: 'Guava' },{ name: 'Tangerine' },
        { name: 'Kiwi' },{ name: 'Lychee' },{ name: 'Strawberries' }, { name: 'Watermelon' }],
    };
  },
  methods: {
      userSelection(listItemName) {
      this.nameList = [];
      if (listItemName === 'ListAll') {
        for (const value of this.names) {
          this.nameList.push(value.name);
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.listitems {
display: flex;
justify-content: center;
}

ul {
    list-style-type: none;
}

.grid-container {
    display: grid;
    grid-template-columns: auto auto auto auto;
    padding: 10px;
}

.grid-item {
    text-align: center;
}

.new-line:last-child {
    content: '\a';
    white-space: pre;
}

.break {
    flex-basis: 100%;
    height: 0;
}
</style>

Answer №1

This code snippet is designed to iterate through a list of names and display them in an alphabetized manner, adding a line break whenever the first letter of one name does not match the previous name. It assumes that the list is already sorted alphabetically.

<div v-for="(name, index) in nameList" :key="name" class="grid-item">
    <ul v-for="alphabet in alphabets" :key="alphabet">
        //a BR or any other element you prefer
        <br v-if="i > 0 && nameList[i-1].name.charAt(0) !== name.charAt(0)"/>
        <li v-if="name.startsWith(alphabet)"><a>{{ name }}</a></li>
        <div class="break"></div>
    </ul>
</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

Directive in AngularJS is a reusable component that allows

Let me explain my situation. I am dynamically adding a block of code using JavaScript and binding it to my AngularJS scope. Everything seems to be working fine, except for one issue. There is a directive on a text box that works properly. However, the $wat ...

What is the method to determine if a date is larger or smaller than another using Javascript?

Using the inputText function retrieves the value entered in the textbox, while the hidden field value returns the current value. This is my current code snippet: if (inputText.value.length != 0) { if (inputText.value < document.getElementById(&apo ...

What is the process for adjusting the expiration time of a GitLab accessToken?

I am currently using NextAuth for logging in with GitLab, but I am encountering an issue where my accessToken changes every 2 hours. How can I ensure that it remains valid for a longer period so that I can successfully store it in my database? It's wo ...

Sending both an array and an image via Ajax in a single request

I need to send both JSON and file data to my PHP backend using an ajax call. Here is my current ajax call: $.ajax({ type: 'POST', dataType: 'json', data: jsonData, url: 'xxx.php', cache: false, suc ...

The sidebar's background is cut off before reaching the bottom when scrolling

I have been working on creating a sidebar that includes a background image with a transparent overlay. However, I encountered an issue where the overlay background does not stretch all the way to the bottom when the scroll bar becomes visible. Despite sett ...

Discovering the presence of a NAN value within a JSON string

Consider the following scenario: I have a function that receives jsonData in JSON format, and I want to validate the variable jsonData to check for NaN. How can I achieve this? function save() { var jsonData = getEnteredValue(); $.ajax({ ...

What is the fewest amount of commands needed to generate a client-side Javascript code that is ready for use?

In the realm of JavaScript libraries found on Github, it has become increasingly challenging to integrate them directly into client-side projects with a simple script tag: <script src="thelibrary.js"></script> The issue arises from the browse ...

Preventing scrolling in one div while focusing on another div

I am currently in the process of creating a website that functions as a single page site. The main feature of the site is a masonry grid of images. When a user clicks on an item, a detailed panel slides in from the left. Once the panel is closed, it slide ...

Prevent drag and drop functionality in QtWebkit

As I work on creating an HTML GUI for my application using Qt's WebKit, everything is going smoothly with one minor issue. I am trying to prevent users from dragging and dropping images from the GUI itself. While I have successfully disabled text sele ...

Trouble arises when attempting to delete rows from my database with the use of HTML, PHP, and

I am developing an application where I have implemented this table: <?php require_once 'Connect2db3.php'; ?> <form> <fieldset> <article class="rondehoeken"> <header> <div class="streep1"></div& ...

Distinguishing Design with CSS3

Here is the code snippet I am using: <table width="562" cellspacing="0" cellpadding="0" border="0" align="center" class="genericClass"> (nested tags are here) </table> These are the related styles in my stylesheet: table.genericClass a ...

Unchecking an available item observable in Knockout.js when clicking on a selected item

When you click on the elements in the top list, a selection is made. If you click on the elements in the bottom list, it will be removed from the list. However, the checkbox in the top list is not being unchecked. How can this issue be resolved? functio ...

Replacing an array element in React.js

Here is a React.js code snippet where I am trying to utilize an array called distances from the file Constants.js in my Main.js file. Specifically, I want to replace the APT column in the sampleData with a suitable value from the array distances extracted ...

The Step-by-Step Guide to Adding a Function Style to Wordpress

Typically I would use enqueue in this manner wp_enqueue_style( 'mystyle', get_stylesheet_directory_uri() . '/css/style.css',false,'1.1','all'); but now I have created a custom field and need to enqueue a style that ...

Is it possible to configure the Eclipse Javascript formatter to comply with JSLint standards?

I'm having trouble setting up the Eclipse Javascript formatting options to avoid generating markup that JSLint complains about, particularly with whitespace settings when the "tolerate sloppy whitespace" option is not enabled on JSLint. Is it possible ...

Navigating a Multi-Page Website with Sleek Scrolling

I've been searching for a solution everywhere but haven't had any luck. I'm trying to implement a smooth scroll effect that works seamlessly across multiple pages. For instance, the smooth scroll effect is present on the homepage with naviga ...

An addition operation in Javascript

Recently, I dipped my toes into the world of Javascript. However, I found myself puzzled by the script and its corresponding HTML output provided below. Script: <h1>JavaScript Variables</h1> <p id="demo"></p> <script> var ...

Is it possible to clear a div using jQuery and then restore its contents?

In my setup, I have a video player within a div where clicking the play button (.video-play-container) fades in the video, and clicking the close button (.close-video) fades it out. The issue arose when the faded-out video continued playing in the backgr ...

Issues with VueJS rendering have been observed on MacOS with both Safari and Chrome browsers

Encountering an unusual issue here. My VueJS application, sourced from CDN, incorporates Vuetify. Interestingly, it functions seamlessly on Ubuntu and Windows; however, my client reports observing raw VueJS code when accessing the app via Safari on his iP ...

Steps for updating text within an object in Angular

details = [ { event: "02/01/2019 - [Juan] - D - [Leo]", point: 72 }, { event: "02/01/2019 - [Carlo] - N - [Trish]", point: 92 } ]; I am attempting to modify the text within the titles that contain - N - or - D - The desired outcom ...