Display the data count of a filtered list in Vue 2

As a newcomer to Vue, I am facing what seems like a simple and common task but the solution is escaping me. I need to filter some data and then display the count in a component.

This is the HTML structure:

<main class="container-fluid">
    <div class="row" id="main-app">
        <div class="col">
            <div class="card border-secondary mb-3" style="min-height: 400px;">
                <div class="card-body">
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" placeholder="Find Items" v-model="search">

                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-8">
            <div class="card border-secondary mb-3">
                <div class="card-body">
                    <h4 class="card-title">Items <item-counter :count="resultCount"></item-counter></h4>
                    <div class="row">
                        <div class="col" id="results">
                            <ul class="list-group list-group-flush">
                                <li class="list-group-item" v-for="app in filteredApps" :key="app.id">
                                    <div class="d-flex w-100 h-100 align-self-center">
                                        <a :href="app.link">{{app.name}}</a>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

Incorporating Vue JS:

var ItemCounter = Vue.component('item-counter', {
  props: ['count'],
  template: '<span class="badge badge-primary badge-pill">{{ count }}</span>'
});

var vmResults = new Vue({
  el: '#main-app',
  data: {
    search: '',
    items: [
      {
        "id": 1,
        "name": "Item 1",
        "link": "https://www.google.com"
      },
      {
        "id": 2,
        "name": "Item 2",
        "link": "https://www.google.com"
      },
      {
        "id": 2,
        "name": "Item 3",
        "link": "https://www.google.com"
      },
    ]
  },
  computed: {
    resultCount() {
      return this.data && this.data.length;
    },
    filteredApps: function () {
      if (this.search.trim() === '') {
        return this.items;
      } else {
        return this.items.filter(function (item) {
          let self = this;
          return item.name.toLowerCase().indexOf(self.search.toLowerCase()) >= 0;
        });
      }
    }
  },
  components: {
    ItemCounter
  }
});

The strategies I have attempted so far have not been successful. I am encountering errors with the search functionality and unable to display the count. Can someone please point out what I might be missing?

Link to jsfiddle for reference

Answer №1

  • A duplicate id ([1, 2, 2]) has been identified
  • The use of the self/this method is not effectively preserving this from outside the function scope

To address this issue, consider implementing an es6 arrow function instead:

filteredApps: function() {
  if (this.search.trim() === '') {
    return this.items;
  } else {
    return this.items.filter(item => { // <-- es6 arrow function preserves `this`
      return item.name.toLowerCase().indexOf(this.search.toLowerCase()) >= 0;
    });
  }
}
  • The variable resultCount should provide the length of the filtered results:
resultCount() {
  return this.filteredApps.length;
}

You can also view the updated fiddle for reference: Updated fiddle

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

Invoking a class method in Javascriptcore on iOS

I'm currently trying to comprehend the inner workings of JavascriptCore. Initially, I attempted calling a single function. Now, my focus has shifted to invoking a function within a class. This is what my javascript code looks like: var sayHelloAlf ...

Verify if session is in existence

Currently in the process of setting up my NodeJS and Express App, utilizing Passport for authentication through Google Sign In and Login. All functionalities work flawlessly when tested on localhost. The sign-in process is smooth, and upon checking, I can ...

My AngularJS ng-show functionality is not functioning as expected. I have already reviewed the syntax and still encountering issues

Having trouble with my ng-show, it's not functioning as expected <div class="form-group"> <label class="control-label col-sm-4">NotesTest:</label> <div class="col-sm-4"> <textarea class="form-control ...

Detecting attribute changes in AngularJS directivesGuide to detecting changes in attributes within Angular

Combining jquery ui and angularjs in my project has been a great experience. I have created a custom directive as shown below. app.directive('datepicker', function() { return { link: function (scope, element, attrs) { elem ...

Executing npm scripts in Node.js

Trying to move away from using the likes of Grunt or Gulp in my projects, I've been exploring npm-scripts as a potential replacement. While npm-scripts makes use of `package.json`, I've found that more advanced build processes require command lin ...

Ways to access JSON data in JavaScript

I'm experiencing difficulty accessing the JSON data provided below. My approach involves utilizing the JavaScript AJAX success function, and when attempting alerts with the following code, $.ajax({ type:'GET', url:myURL, success : function ...

Separating the logic of identical schemas and implementing multi-tenancy in Node.js using Mongoose

In the system I am developing, there are two key requirements: Each client needs to be completely isolated from one another Clients can have multiple subsidiaries which they should be able to switch between without needing to re-authenticate, while ensuri ...

The initial value for React input is vacant and is not capturing either the state or the prop value

After utilizing Vue for an extended period, I have now transitioned to React. To practice, I am attempting to convert some basic Vue components into React. My initial Vue code was simple as shown below: <template> <div> <h1>Hello { ...

The Axios API request is made, but fails to retrieve any data back to the client

I've been working on a feature in my VueJS app where I need to restrict page viewing of an Upload instance to only members of a specific Group. However, I'm facing an issue with retrieving the group information. Despite axios successfully hittin ...

What is the best way to update a specific value in an object without affecting the rest of

Below is a data object: { name: "Catherine Myer", age: 23, birthday: "august" } If I want to pass this data as a prop to a component, but also change the age to 24, how can I do that? <NextPage data={author.age = 24}/> The ...

How can I remove markers from google maps?

I have been working on a program that dynamically loads JSON data onto a map as markers when the user pans and zooms. However, I am facing an issue where I need to clear the existing markers each time the user interacts with the map in order to load new on ...

Share content on Facebook using a single-page application

This inquiry may not be specifically tied to a particular software stack, framework, or coding language. In the current project I'm working on, we are utilizing AngularJS for developing the front-end with a static landing page that loads real data an ...

Bootstrap 4 Card Body Spinner Overlay with Flex Alignment

Seeking to center a spinner both vertically and horizontally within a bootstrap 4 card body. Despite trying my-auto, justify-content-center & align-items-center, it seems like I'm missing something. I've double-checked the display types and ...

Enhancing code with new Javascript functionality

Currently utilizing the WordPress Contact Form 7 plugin and in need of updating my existing JavaScript code to include an onclick function and data-img attribute for checkboxes. Due to the limitations of Contact Form 7 shortcode, adding attributes beyond i ...

No element found with the specified exportAs value of "ngForm" on the <form> tag

I am currently experimenting with a template driven form in Angular, but I encountered an error stating **There is no directive with “exportAs” set to “ngForm"** I have made sure to import FormsModule and ReactiveFormsModule in app.module.ts as well ...

Is it possible to use Typescript to store and access static global variables based on a unique key

I want to store variables in a static global file, like this: declare const MYVAR = 'Some unchanging data'; Later on, I would like to be able to retrieve the information using just the key 'MYVAR', for example: globalFile.findValue ...

What is the best way to insert a record into the rth column of the nth row in a table

In the table I'm working with, there are 6 columns and only 5 of them have data filled in. The last column is currently empty for all rows. I am now trying to populate the last column of each row with some data. Can someone guide me on how to use a f ...

Is there a way to customize the outlined color of an input adornment in MUI?

Looking to customize the default blue color in a Form Control outlined variant, but can't figure out how. I was able to do it with a regular TextField, but this one is a bit trickier. <FormControl variant="outlined"> < ...

The value remains constant until the second button is pressed

I have a button that increments the value of an item. <Button bsStyle="info" bsSize="lg" onClick={this.addItem}> addItem: addItem: function() { this.setState({ towelCount: this.state.towelCount - 2, koalaCount: this.state.koalaCount + 2 ...

Implementing conditional navigation in app.vue based on the user's login status retrieved from the main.js file

I need to display a different navigation in app.vue based on whether the user is signed in or not. I have seen some complex solutions, but I'm wondering if there is a simple if/else solution or a way to pass a function from main.js to vue.js? Thank yo ...