How to exclude the initial iteration in a v-for loop in VueJS2?

I am currently working on a project using Laravel 5.5, Vue.js 2, and Lodash. I am trying to skip the first incoming data in the result, similar to the image shown below. Below is the code for my Vue.js 2 implementation:


new Vue({
el:'#users',
data:{
    message:'',
    ok:false,
    noresult:false,
    arrayresults: [{id:'' ,username: '',useremail: '',userphone:'',}],  
},
methods:{
    searchData: _.debounce(function(){
        if(this.message != '')
        {
            this.noresult = false;
            this.arrayresults = [{id:'' ,username: '',useremail: '',userphone:'',}],    
            $.ajax({
                type:'POST',
                url: path+'usersearch',
                data: {data:this.message},
                success:(data) => {
                    if(data.length >= 1)
                    {
                        for(i = 0;i<data.length;i++)
                        {
                            this.arrayresults.push({id:data[i]['id'],username:data[i]['user_name'],useremail:data[i]['user_email'],userphone:data[i]['user_phone']})
                        }
                        this.ok = true;
                    }
                    else
                    {
                        this.ok = false;
                        this.noresult = true;
                    }
                 },
                error:function()
                {
                    console.log("error");
                }
            });
        }
        else
        {
            this.ok = false;
            this.arrayresults = [{id:'' ,username: '',useremail: '',userphone:'',}];
        }
    },1000)
}
});

Here's my Laravel Blade code:


<div v-if="ok" id='search-result' v-cloak>
<table class='table table-responsive thead-text' border='5'>
<thead>
<tr class='success'>
<td>{{trans('language.user_name')}}</td>
<td>{{trans('language.user_phone')}}</td>
<td>{{trans('language.user_email')}}</td>
<td>{{trans('language.settings')}}</td>
</tr>
</thead>
<tbody>
<tr v-for='(arrayresult ,key ,id) in arrayresults' class='warning'>
<td>@{{arrayresult.username}}</td>
<td>@{{arrayresult.userphone}}</td>
<td>@{{arrayresult.useremail}}</td>
<td class='hidden-print'>
<a v-bind:href="'/{{$path}}/users/' + arrayresult.id" class='btn btn-success'>{{trans('language.show')}}</a>
@can('users.update')<a v-bind:href="'/{{$path}}/users/' + arrayresult.id + '/edit'" class='btn btn-info'>{{trans('language.edit')}}</a>@endcan
</td>                       
</tr>
</tbody>
</table>
</div>

Everything seems to be working fine so far except for the issue where the first value appears as null when setting the array like this:


this.arrayresults = [{id:'' ,username: '',useremail: '',userphone:'',}],

The current result looks like this:

https://i.sstatic.net/Pdg1F.png

To resolve this, I aim to eliminate the first null value from the search results.

Answer №1

utilize v-for along with v-if (check out the tutorial)

When both directives are present on the same element, v-for takes precedence over v-if. This implies that v-if will be executed separately for each iteration of the loop. This can come in handy when you need to display elements only for certain items, like in the example below:

UPDATED: Introduced a more efficient method

example:

new Vue({
  el: '#app',
  computed: {
    filteredArray() {
      return this.array.filter(item => !!item.firstName);
    },
  },
  data: {
    array: [
    {
      firstName: '',
      lastName: '',
      age: 0
    },
    {
      firstName: 'Dirk',
      lastName: 'Doe',
      age: 41
    },
    {
      firstName: 'Julia',
      lastName: 'Doe',
      age: 25
    }
    ]
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bacccfdffa88948c948b8b">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <li v-for="user in filteredArray">
      {{ user.firstName }} - age: {{user.age}}
  </li>
  <pre>old array = {{ array }}</pre>
</div>

Answer №2

Revise

this.resultsList = [{id:'' ,name: '',email: '',phone:'',}] 

with

this.resultsList = []

Answer №3

Something Voldymyr penned down

<li v-for="(value, index) in array" v-if="value.firstName">
      {{ value.firstName }} - the position is: {{index}}
</li>

It appears that excluding data with null or empty first names is a sensible choice. However, if you want to skip the very first record specifically, here's a clever workaround:

<li v-for="(value, index) in array" v-if="index">
  {{ value.firstName }} - this is at position: {{index}}
<li>

Since the initial record has an index of 0, v-if(index) will evaluate to false.

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

Using more than one variable for filtering in Vue.js

I've been busy working on implementing table filtering in Vue.js. So far, I have successfully filtered the table by name and date. However, I'm now facing a challenge with adding another filter along with them. If you want to check out my curren ...

What is the Vue.js equivalent of Angular's ng-container?

When working with Angular, you may come across a tag called ng-container which is used in the following way: <ng-container *ngIf="false">this won't be shown</ng-container> According to the Angular documentation: The Angular is a grou ...

Leveraging font display functionality while incorporating a Typekit URL

Pagespeed is giving me a warning, Make sure text remains visible during webfont load I have been researching how to fix this problem and I found people suggesting to include the font-display: fallback argument in the font declaration block. However, I ...

Error 403: Access Denied for Laravel project due to nginx restriction

Upon inheriting a Laravel project, I noticed a unique directory structure that led me to believe it's a Laravel 4.0 project due to the presence of app/storage instead of /storage in the root directory typical of Laravel 5.0 projects. <!-- Directo ...

Arrange a group of users in the middle

Looking for some help with this specific code snippet .selection_user { display: block; background-color: #2D2C31; text-align: center; line-height: 75px; } <div class="select_user_menu"> <div class="selection_user">User1</div> ...

Update the Navbar links to smoothly slide along the navigation bar as the width decreases, instead of awkwardly

When in full screen, the Navbar links are displayed horizontally. https://i.stack.imgur.com/0mOLp.png However, when the width changes, they appear like this https://i.stack.imgur.com/2ylgZ.png Is there a way to ensure they shift to the left while maint ...

Is there a way to keep my fixed footer container from moving while zooming in and out on a webpage

Is there a way to prevent the bottom text from shifting when zoomed in or out on the page? The rest of the content remains stable, but due to using position:absolute for this section to stay at the bottom of another div (content), it causes movement. #con ...

Expanding beyond the dimensions of the webpage, HTML CSS Height set to 100% creates a unique

I'm struggling with the CSS on a page I'm working on. I have a header and main content each enclosed in div tags, with the header set to a height of 250px and the main content set to a height of 100%. I've also set the html and body heights ...

The Quasar straightforward filtering tool fails to effectively filter and transmit data in dynamic scenarios

As I work on implementing a select component with a basic filtering feature, an issue arose. Initially, the select input displays the list correctly. However, upon clicking the select input and attempting to filter by entering keywords, an error occurs a ...

Creating a logo that scales seamlessly across different web browsers while maintaining responsiveness through

I am working on making this logo align perfectly with all screen resolutions and browsers, while ensuring it stays at the exact center (both vertically and horizontally) of the #container. If the resolution drops below 320px, I want the company name to dis ...

Tips for adjusting the position of Google Maps in a responsive layout

My website has a Google Maps page that displays fine on normal browsers, but when viewed in responsive mode (on mobile), the map overlaps with the checkboxes. I want the map to be positioned below the checkboxes in responsive view. How can I achieve this? ...

What are the steps to setting up Webpack-simple with Vue Cli 3?

I'm completely new to Vue Cli and the Vue framework in general, so any help is appreciated! From what I understand, in Vue Cli 2, the command was something like this: Vue init webpack-simple xxx However, with the latest major update (3), it has cha ...

A perfectly organized and justified menu with evenly spaced horizontal list items

I couldn't find a solution to evenly spacing out a series of list items for a menu styled list. After realizing CSS alone wasn't enough, I decided to incorporate some javascript (jQuery). My goal was to have equal padding between each LI without ...

Adjusting background size using jQuery as the window is resized

Exploring ways to dynamically resize the background image of my website based on the current window dimensions using jQuery. At the moment, I have tried the following approach: $(window).resize(function() { $("body").css({"background ...

Tips for enabling the background div to scroll while the modal is being displayed

When the shadow view modal pops up, I still want my background div to remain scrollable. Is there a way to achieve this? .main-wrapper { display: flex; flex-direction: column; flex-wrap: nowrap; width: 100%; height: 100%; overflow-x: hidden; ...

Combine multiple values into a single input in the number field

I have a number type input field... What I am looking for is: Age-Height-Weight 20-180-80 Is there a way to ensure that users input data in this exact format and then have the final result inserted into the input field with type="number" and submitted? ...

Creating a dynamic navbar in an ASP.NET website by populating it with data from a

Seeking guidance on creating a dynamic Bootstrap navbar in an ASP.NET website based on the user's role stored in a database, while maintaining the same style. I have extensively searched for a solution without success. Any assistance would be greatly ...

Guide on passing authorization header from Flask API to VueJS

I've been working on a login page that utilizes JWT for authorization. The backend authorization is functioning properly, but I am encountering an error when trying to authorize the page using axios from VueJS. The error message indicates "Missing aut ...

Create a button animation inspired by Google's Ripple Effect

I came across a website with a button that has a cool Google-like animation. How can I create a similar button that triggers an animation when clicked? Here is the code I have been working on: button { text-transform: uppercase; padding: 0.8em; ...

css Apply styles to form controls only if they are not empty

Utilizing an angularjs form, I have customized the following example to fit my code: .my-5 { margin:100px; } .form-group { position: relative; margin-bottom: 1.5rem; } .form-control-placeholder { position: a ...