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

LESS: Using variable values in mixin and variable names

I am looking to simplify the process of generating icons from svg-files while also creating a png-sprite fallback for IE8 support. I am using grunt.js and less. I was inspired by the implementation on 2gis.ru: (in Russian), where they used technologies s ...

Transform a Vue.JS project into a Nuxt.JS project

Is it possible to transform a Vue.JS project into a Nuxt.JS project? Vue.js Project If you want to view the complete Vue.JS project, click here. This project utilizes the npm package vue-conversational-form to convert web forms into conversations using ...

Ways to update the DOM following modifications to a data attribute

I'm currently working on a small CMS system that handles translations for static pages in multiple languages. The system refreshes and loads translations dynamically, but I've encountered some bugs that are proving difficult to resolve. One issue ...

Do Material-UI pickers only validate on blur, not on change events?

When you type inside the DatePicker component, validation is triggered immediately. Is there a way to trigger validation on blur instead of onChange when using @material-ui/pickers with material-ui v4 Passing the value to the blur function should work a ...

Firestore Query sends data object to browser

When making a Firestore query, the browser is displaying [object Object],[object Object] instead of the expected output: router.get('/jobopportunities', async(req, res) => { var jobArray = []; const snapshot = await fireba ...

Find the identification number by searching through the text

I'm trying to find a way to retrieve the node id during a text search. Here's an example: http://jsfiddle.net/53cvtbv9/529/ I attempted using two methods to get the id of a node after the search: console.log($('#jstree').jstree(true). ...

Diverse Values within the Inner Border

Is it possible to create an inner border with unique values for each side? For instance: Top: 20px Right: 80px Bottom: 40px Left: 10px Can you provide an example of how this can be achieved? Thank you! :) ...

What is the best way to ensure TypeScript recognizes a variable as a specific type throughout the code?

Due to compatibility issues with Internet Explorer, I find myself needing to create a custom Error that must be validated using the constructor. customError instanceof CustomError; // false customError.constructor === CustomError; // true But how can I m ...

Dynamic routing with Vue

Currently in the process of developing an application and encountering an issue with my code pertaining to dynamic routing. Utilizing Firebase to fetch data for the app, each department in the database should generate a navbar. Upon clicking on a specific ...

How come submitting a form without refreshing does not update the database with new values?

I'm encountering an issue with my form and script that is supposed to connect to the operation.php class. Despite having everything set up correctly, the data is not being added to the database and the page does not refresh. I'm perplexed as to ...

Troubleshooting Vue.js unit test issues caused by log messages from internal components

I am working with a component structured like this: <template> <p>{{ message }}</p> <internal-comp></internal-comp> </template> <script> import InternalComp from './components/InternalComp.vue'; ...

What is the best way to decrease the size of a SELECT element in Bootstrap 3?

Is there a way to combine form-control and input-mini classes in order to create a SELECT element with a width of around 60px and a height of approximately 20px? <select id="RoleSelect" class="form-control input-mini { width: 60px; }" runat="server"> ...

display a new feature immediately upon the user's login

I encountered a scenario where the user is supposed to log in, and upon successful login, another component should be displayed. However, this functionality is not working as expected for me. I have to click the login button again or refresh the page to vi ...

A guide on parsing a nested JSON file with ExtJS 4

Here is the content of my JSON file named "jobInfo.json": { "job": { "id": 1, "name": "Job 1", "description": "bla bla bla", "locations": { "type": "FeatureCollection", "features": [{ "id": 1, "t ...

Adding a div to the preceding div based on matching IDs in AngularJS

Here is a representation of my layout in HTML: <div ng-repeat="message in messages"> <div ng-class="{'messages messages--sent': userId == message.id, 'messages messages--received': userId != me ...

Guide on how to set up routing for a Rails 5 API single page application with numerous static entry points

I'm having trouble figuring this out for some reason. My Rails 5 API app is only serving JSON. I have two VueJS front-end apps, one for the public and one for private "admin." My goal is to serve both of these static HTML files from the Rails public ...

Change the size of the font with a slider in VueJS

I have been utilizing the project found at This particular project allows end-users to reuse Vue components as editable sections by providing a styler overlay for adjusting content within a div or section. After installation, I added a slider which now ap ...

What is the best way to showcase a component using FlatList?

Discovering the power of React Native combined with TypeScript and Redux Toolkit Hello! I'm currently facing an issue with rendering a list of messages using FlatList. Everything renders perfectly fine with ScrollView, but now I need to implement inf ...

utilize dynamic variables in post-css with javascript

Question: Is it possible to dynamically set or change variables from JavaScript in post-css? I have a react component with CSS3 animations, and I want to set dynamic delays for each animation individually within each component. I've found a similar s ...

Creating a versatile tabbed interface with Vue.js for multiple uses

I am currently working on integrating a tabbed reusable component in vueJs, but I encountered an issue stating that a specific component is not defined. Below, you will find the code snippets for both components: //TabComponent <template> <di ...