Filtering an Array in VueJS Based on User Input

Currently, I am working on a application where my goal is to filter an array based on user input from a form.

The issue I am facing is that the array named autocomplete is not being populated with visitors that match the query of the first name.

This is a snippet of my HTML code:

<input class="input" placeholder="First Name" v-model="visitor.first" @keyup.enter="searchVisitors">

And here is my Vue Instance code:

new Vue({

  el: '#app',

  data: {
    previousVisitors: [],
    autocomplete: [],
    visitor: {}
  },

  mounted() {
    axios.get('/visitors/all').then(response => this.previousVisitors = response.data);
  },

  methods: {

      searchVisitors(){
        var q = this.visitor.first;
        this.autocomplete = this.previousVisitors.filter(item => {return item.firstName === q});
        console.log(this.autocomplete);
      }
   }
});

I have verified that the response from the axios call, which populates the previousVisitors array, contains the firstName of each previous visitor.

What could be the mistake in my implementation?

Answer №1

Your v-model is currently set to visitor.first, but you are filtering based on firstName.

To correct this, update your code to use

v-model="visitor.firstName"
.

Additionally, there are some potential issues that may cause problems in the future. Firstly, you are dynamically adding a value to visitor, which could lead to reactivity issues. It's recommended to initialize that value properly.

data: {
  ...
  visitor:{firstName: ''}
}

Furthermore, it would be better to utilize a computed value for the filter. Below is a complete example showcasing this approach.

console.clear()

const visitors = [{
    firstName: "bob"
  },
  {
    firstName: "mary"
  },
  {
    firstName: "susan"
  },
  {
    firstName: "Phillip"
  },

]


new Vue({

  el: '#app',

  data: {
    previousVisitors: [],
    visitor: {
      firstName: ''
    }
  },

  mounted() {
    // axios.get('/visitors/all').then(response => this.previousVisitors = response.data);
    setTimeout(() => this.previousVisitors = visitors)
  },
  computed: {
    autocomplete() {
      return this.previousVisitors.filter(v => v.firstName === this.visitor.firstName)
    }
  }
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2b4b7a782f0ecf0ecf4">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <input class="input" placeholder="First Name" v-model="visitor.firstName"> {{autocomplete}}
</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

Can you explain how I can declare a variable to store a scraped element in Puppeteer?

const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ headless: false, defaultViewport: null }) const page = await browser.newPage() await page.goto('https://www.supre ...

React Material Table - issue with data filtering accuracy

Currently in my React project, I am utilizing Material Table. While everything appears to be rendering correctly, the filtering and searching functionalities are not working as expected. To provide more context, below is a sample of the code: ht ...

Creating Interactive Graphs with HTML and JavaScript: A Guide to Dynamic Graph Drawing

I am seeking to create a dynamic graph using standard HTML, JavaScript, and jQuery (excluding HTML5). The nodes will be represented by divs with specific contents, connected by lines such as horizontal and vertical. The ability to add and remove nodes dyn ...

Vue.js encountered a problem with chokidar stating: "Error: EBUSY: resource busy or locked, lstat 'C:hiberfil.sys'"

Description Whenever I execute the command npm run serve, I encounter the following error: ERROR Failed to compile with 1 error 15:34:19 This dependency was not found: * ... in ./node_ ...

Adding a value to an element in JavaScript to interact with it using Selenium

After implementing the provided code snippet, I noticed that it replaces the value in the element with a new one. However, I am looking to append or insert a new line rather than just replacing the existing value. Is there an alternative command like app ...

Challenges with fetching data from APIs in NextJs

I am currently working on a basic NextJs TypeScript application with the app router. The following code is functioning correctly: export default async function Page() { const res = await fetch("https://api.github.com/repos/vercel/next.js"); ...

Strategies for retrieving the latest content from a CMS while utilizing getStaticProps

After fetching blog content from the CMS within getStaticProps, I noticed that updates made to the blog in the CMS are not reflected because getStaticProps only fetches data during build time. Is there a way to update the data without rebuilding? I typica ...

How to Access a Method from Controller 2 in AngularJS Controller One

angular.module('starter.controllers', []) .controller('controller1',function($scope) { $scope.function1= function () { // Code for controller1 function } }) .controller('controller2',fun ...

Can the Browser width/document width be maintained when shrinking the browser window size?

https://i.stack.imgur.com/a4gfA.pngLooking for a solution to maintain the browser/document width at 350px, preventing users from minimizing the window. The desired width is actually 400px, not 350px. Please refer to the image above. I require the window ...

What modifications need to be made to the MEAN app before it can be deployed on the server?

Following a tutorial on Coursetro, I was able to successfully build an Angular 4 MEAN stack application. However, when it comes to deploying the app on a server running on Debian-based OS, I am facing some challenges. The application should be accessible o ...

Ways to send response data back to the parent template in Vue.js following an API request

In my current setup, I have a parent template with two child templates. The first child template makes an API call during its creation process. Following this API response, certain operations need to be carried out in the second child template. To achiev ...

Executing a Root Hook Plugin Prior to Running All Mocha and Playwright Tests

I've recently incorporated automated tests into my Vue.js project by installing this useful plugin. The Vue.js application was initially set up using vue-cli. Everything is running smoothly, and I must say Playwright is proving to be a remarkably ro ...

Tracking user session duration on a React Native app can be achieved by implementing a feature that monitors and

I'm currently focusing on tracking the amount of time a user spends on the app in minutes and hours, and displaying this information. I have successfully implemented the functionality to count minutes, but I am struggling to figure out how to track wh ...

What is the best way to retrieve the parameters from the current URL within an Express function on the backend? (details below)

Struggling to articulate my issue here. I'm in the process of creating a straightforward express app that utilizes the omdb API to search for movie titles and display the results. The challenge is that the omdb API returns the results in pages, with 1 ...

Preserving the button's state when clicked

Here is my code snippet: <blink> const [thisButtomSelected, setThisButtomSelected] = useState(false); var thisButton = []; const onAttributeClick = (e) => { thisButton[e.currentTarget.value] = { thisID: e.currentTarget.id, thisName: e. ...

What is the best method for sending a PHP variable to an AJAX request?

I am working with three files - my main PHP file, functions.php, and my JS file. My challenge is to pass a PHP variable to JavaScript. Below is a snippet from my MAIN PHP FILE: function ccss_show_tag_recipes() { //PHP code here } Next, here's t ...

"Oops, it seems like there are an excessive number of connections in Express MySQL causing

While programming in Angular and creating an API server in Express, I encountered a minor issue after spending hours coding and making requests to the API. The problem arises when the maximum number of requests is reached, resulting in an error. Everythin ...

Running the Express service and Angular 6 app concurrently

Currently, I am in the process of developing a CRUD application using Angular6 with MSSQL. I have managed to retrieve data from my local database and set up the necessary routes, but I am encountering difficulties when it comes to displaying the data on th ...

Can one conceal the JavaScript code that has been written?

Can JavaScript (jQuery) codes be hidden from view? I have a program with several load() functions and I'm worried that everyone can see the page addresses. Is this a risk? Example code snippet: load('account/module/message/index.php'); ...

What could be causing me to have to click the button twice in order to view my dropdown list? Any suggestions on how to

I am facing an issue where I have to click twice on the "Action" button in order to see my dropdown list. How can I resolve this? Is there a way to fix it? $(document).ready(function() { $(".actionButton").click(function() { $dropdown = $("#cont ...