Exploring the method to search across various fields in Vue.js 2

In my Vue.js 2 application, I am attempting to search or filter through three fields: firstname, lastname, and email. Unlike Vue 1, Vue 2 does not include a built-in filter method. As a result, I have created a custom method that can only filter through one field at a time. How can I extend this functionality to multiple fields? I have tried using the

filterBy(list, value1, value2, value3)
approach, but it has not been successful.

Below is an excerpt from my code:

<template>
<div class="customers container">
<input class="form-control" placeholder="Enter Last Name" v-
model="filterInput">
<br />
<table class="table table-striped">
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="customer in filterBy(customers, filterInput)">
      <td>{{customer.first_name}}</td>
      <td>{{customer.last_name}}</td>
      <td>{{customer.email}}</td>
      <td><router-link class="btn btn-default" v-bind:to="'/customer/'+customer.id">View</router-link></td></tr>
  </tbody>
</table>

</div>
</template>

<script>

export default {
name: 'customers',
data () {
return {

  customers: [],
  filterInput:'',

}
},

methods: {
fetchCustomers(){
  this.$http.get('http://slimapp.dev/api/customers')
    .then(function(response){

      this.customers = (response.body); 
    });
 },

 filterBy(list, value){
    value = value.charAt(0).toUpperCase() + value.slice(1);
    return list.filter(function(customer){
      return customer.last_name.indexOf(value) > -1;
    });
  },


  },

  created: function(){
  if (this.$route.params.alert) {
  this.alert = $route.params.alert
  }
  this.fetchCustomers();
  },

  updated: function(){
  this.fetchCustomers();
  },
  components: {

  }
  }
  </script>

  <!-- Add "scoped" attribute to limit CSS to this component only -->
  <style scoped>

Answer №1

Enhance your filterBy function to search for more than just the last name

filterBy(list, value){
    value = value.charAt(0).toUpperCase() + value.slice(1);
    return list.filter(function(customer){
      return customer.first_name.indexOf(value) > -1 ||
             customer.last_name.indexOf(value) > -1 ||
             customer.email.indexOf(value) > -1
    });
  },

Consider utilizing computed properties to generate filtered outcomes (which could improve performance due to caching)

computed: {
  filteredList() {
    const value= this.filterInput.charAt(0).toUpperCase() + this.filterInput.slice(1);
    return this.customers.filter(function(customer){
      return customer.first_name.indexOf(value) > -1 ||
             customer.last_name.indexOf(value) > -1 ||
             customer.email.indexOf(value) > -1
    })
  }
}

Implement it within your template like this

<tr v-for="customer in filteredList">
 ...
</tr>

Answer №2

If you're searching for a specific word, this method will locate all strings that START with the word you input and will ignore any words in between sentences.

For instance, if you have a customer named Vincent Van Patten, you would only find it by searching for Vincent or Vincent(space)Van. Searching for just Van or Patten won't yield results because of how indexOf is being utilized in the filter function.

This is why using JS includes() might be preferable:

computed: {
  filteredList() {
    const value = this.filterInput.charAt(0).toUpperCase() + this.filterInput.slice(1);
    return this.customers.filter(function(customer){
      return customer.first_name.includes(value) ||
             customer.last_name.includes(value) ||
             customer.email.includes(value)
    })
  }
}

Now, searches for terms like Van or Patten will yield matches.

Answer №3

To enhance its flexibility, consider converting to lowercase:

computed: {
    filteredList() {
        const value = this.filterInput.toLowerCase().slice(1);
        return this.customers.filter(function(customer){
            return customer.first_name.toLowerCase().indexOf(value) > -1 ||
            customer.last_name.toLowerCase().indexOf(value) > -1 ||
            customer.email.toLowerCase().indexOf(value) > -1
        })
    }
}

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

What is the best way to make a CSS element move with Javascript?

Currently working on a JavaScript game where I am in need of a CSS object to replace the original JavaScript object. Specifically, I want my "sword" CSS object to move along with my player object when it is Unsheathead. All the examples I find only show wh ...

Is there a way to convert this asynchronous function into a synchronous one so that it returns the value immediately

When it comes to making a Nodejs/Javascript method synchronous, there are several solutions offered by the community. Some suggest using libraries like async and fibrous, but these involve wrapping functions externally. However, I am in search of a soluti ...

How to use jQuery to set a background image using CSS

I've been working on setting backgrounds dynamically with a jQuery script, but it seems like the .css function is not working as expected. Here's the code snippet: $(document).ready(function () { $(".VociMenuSportG").each(function () { ...

Developing applications using ReactJS with Typescript can sometimes lead to errors, such as the "onclick does not exist on type x

In the code snippet below, I have a method that renders a delete icon and is used in my main container. Everything functions correctly except for a small cosmetic issue related to the type any that I am struggling to identify. import React from 'reac ...

Error encountered when attempting to include a foreign key

I am attempting to establish a 1:1 relationship between two tables. The RefreshToken table will contain two foreign keys connected to the Users table, which can be seen in this image: https://i.stack.imgur.com/B2fcU.png To generate my sequelize models, I ...

Vue js not displaying real-time data changes in Percircle Dynamic

I'm currently utilizing the percircle JS library in conjunction with vue js. The issue I'm encountering is that when data is received from the API, it doesn't immediately show up in the percircle. However, if I rerun the API request, the ch ...

Adjust the class based on the model's value in AngularJS

items = {'apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby'} html <div class="variable" ng-repeat="item in items">{{item}} </div> ...

Having trouble with IE7 - unable to interact with elements below popup form

<script type="text/javascript">var switchTo5x=true;</script> <script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script> <script type="text/javascript">stLight.options({publisher:'b42661f5-2dc5 ...

Tips on locating information within a pre-existing GET array with parameters provided

Apologies for the unclear title. I am currently utilizing a category chooser that pulls categories from an API. The process involves fetching a list of categories, filtering out their names, and presenting them in the category chooser. Upon clicking submit ...

Which HTML tags can be activated with JavaScript to be interactive?

I'm currently diving into the world of JavaScript and one of the initial code snippets I've encountered is onclick. So far, I've seen it utilized in form buttons like this: <input type="button" onclick="checkName()" value="Check name" / ...

The data retrieved from the PHP script is not accessible within the main Vue instance

I am currently working on a Vue.js component for a modal window. Once the user fills out all the necessary data in the fields, I need to achieve the following: Send the data to the server. Apply a timeout to show the user that the data is being sent (by ...

How can I retrieve the selected value from an Angular 2 dropdown menu when it changes, in order to utilize it within a function?

I am currently working on creating a dropdown menu with multiple options. When a user selects an option, I need to make an API call that requires an ID parameter. Inside my component.ts file, I have defined an array containing the values like this: valu ...

Issue with GMap Compatibility on Specific Web Browsers

I'm currently facing an issue with implementing gMap [1] on a website. The map is functioning properly in Chrome and Safari, but it fails to display in Firefox, IE, and Opera (latest versions of all). I have ensured that the Google Map API key loads a ...

Using AngularJS to dynamically assign classes with values derived from an ng-repeat loop

I'm attempting to assign a class to a table row using ng-class based on the value of ng-repeat. I have searched online and found examples that involve calling a function. Is it possible to simply set ng-class with a value instead of using a function? ...

Scrolling to ID or Anchor using jQuery: Automatically scrolls to the top if already at the designated section

I've been on a quest to uncover the cause and solution for this issue. Lately, I've been utilizing $("#content").animate({scrollTop:$(#elementId).offset().top-183}, 600); to achieve smooth scrolling to an ID within a <div>. The number 18 ...

Tips for conducting an HTTP request test within my application

I am currently facing a challenge while attempting to develop unit tests for my application. Within my controller, I have the following code snippet: $scope.test1 = function() { productFactory.getName() .then(function(products){ ...

Vue: updating the :root CSS variable for a child component leads to an error - TypeError: Unable to access properties of undefined (reading 'style')

Fiddle: https://codesandbox.io/s/hardcore-mestorf-w1lsob?file=/src/App.vue In my project, I have created two simple files that are responsible for displaying a circle on the screen: https://i.stack.imgur.com/0ddI3.png The goal is to modify the circular ...

Create a dynamic animation using Angular to smoothly move a div element across the

I currently have a div with the following content: <div ng-style="{'left': PageMap.ColumnWrap.OverviewPanelLeft + 'px'}"></div> Whenever I press the right key, an event is triggered to change the PageMap.ColumnWrap.Overvie ...

What could be causing the issue of $.ajax being undefined while utilizing jQuery in Node.js?

I'm currently testing a module on Node.js that is meant for client-side use. In order to make $.ajax work, I need some guidance. To begin with, I have installed jQuery on the project using: $ npm install jQuery Despite this, when I try to access $. ...

Receiving the outcome of an asynchronous function in JavaScript

async function retrieveKey() { try { var key = await dec.awsDecrypt('dev-frontend') return key; } catch(err) { } } //calling the function const result = retrieveKey() In the code snippet above, there is an asynchronous ...