Having trouble with Vue.js array filtering feature in my program

My Vue.js code includes a search input with a dropdown menu populated by an API data array called categories. I am attempting to implement a filter on the search input so that when a value is typed, it filters the dropdown menu items based on the API data. However, my current code does not seem to be applying the filter correctly. Can anyone provide assistance?

<template>

  <div class="dropdown">
    <input v-model.trim="inputValue" class="dropdown-input" type="text" placeholder="Find country" />
    <div v-show="inputValue" class="dropdown-list">
      <div   v-for="(category, index) in FilterCategories"
              :key="index" class="dropdown-item"
            {{ category.category_name }}

      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import questionService from "../services/questionService";

export default {
  name: "postComponent",
  components: {},
  
  data() {
    return {
      inputValue: '',
      categories: [],
   
    };
  },
  methods: {
       FilterCategories() { //not working
   
        return  this.categories.filter(categories => {
        return categories.category_name===this.inputValue
        });
     
    },},
    
  mounted: function () {
    questionService.getCategories().then((response) => {
      this.categories = response.data.response;
      
     
    });
  },
};
</script>

Answer №1

It is recommended to utilize the computed property for better performance.

computed: {
       FilterCategories() {
        return this.inputValue ? this.categories.filter(category => {
          return category.category_name.toLowerCase().includes(this.inputValue.toLowerCase())
        }) : this.categories;  
    }
}

**No modifications needed in template

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 can be done to mute [Vue-warn] during prop validation?

Is there a way to suppress the default Vue warning [Vue-warn] when displaying a custom validator message on a prop? I am currently seeing both the custom error message and the Vue warning. This is what my prop looks like: props: { mode: String, defaul ...

Transforming a fluid webpage into a fixed page

Currently, I am undertaking a project that involves converting a dynamic website like Adobe Spark into a static HTML+CSS page, which will eventually be transformed into a PDF. The interactivity of the website relies heavily on Javascript modifying CSS+HTML ...

Guide on detecting and capturing a change in location history event

My main goal is to capture router change events outside of the NextJS framework, not within it. The application I have developed using NextJS includes some code that operates independently of the NextJS context. This code needs to be able to detect navigat ...

Create a pair of variables by utilizing the split function

I have a string that looks like this test/something/else My goal is to create two separate variables: first = test second = something/else I attempted to achieve this using the following code snippet: const [first, ...second] = "test/something/else& ...

What is the process for registering a click using a class in jQuery and retrieving the ID of the clicked element?

Currently, I am working on developing a webpage where I need to use jQuery to register a click using the items class and then extract the ID of that particular object. For example: HTML: <div class="exampleclass" id="exampleid1"></div> <d ...

Swap image in div upon hovering over a list of links in another div

I'm in the process of designing a webpage that features a header and footer fixed to the top and bottom of the browser window, with adaptable content in between. To structure the inner content, I've opted for a flexbox wrapper containing a list o ...

Using JavaScript, what is the process for getting the value of a child node within Firebase

var ref = firebase.database().ref("games/" + gameId + "/patterns"); ref.on("child_changed", function(snapshot){ var pattern = snapshot.key; console.log(pattern); }); Currently, the code snippet above only logs the key. But how can I extract the player ...

Associate the class instance function with the v8::FunctionTemplate

I am relatively new to C++ and v8, with the aim of creating a native node.js addon. However, I have hit a roadblock on what seems like a simple issue to me. The error message C:\Path\To\Project\File.cpp(50): error C2664: 'v8::Loc ...

react-responsive-carousel: setting a specific height for thumbnail images

After setting a fixed height for the image, I noticed that the same height is also being applied to the thumbnails. How can I avoid this issue? <Carousel width="600px" dynamicHeight={false}> {data?.book?.images.map((image, i) => ( ...

Leveraging the power of Vue.js by incorporating various instances of pagination

Is there a way to use multiple instances of Vue.js's Pagination plugin within a loop effectively? Consider this example for (let i in sources) { // create a new tab with its own pagination } I am facing an issue where the @page-changed="pageCha ...

Express: router.route continues processing without sending the request

I've implemented the following code in my Express application: var express = require('express'); // Initializing Express var app = express(); // Creating our app using Express var bodyParser = require(' ...

Making a Call with Twilio using Node.js

Currently, I am working on a click-to-call website that is powered by Twilio. The process involves configuring a TwiML app and writing Twilio JavaScript SDK client-side to send requests to Twilio. Once this is done, Twilio will initiate a POST request to t ...

Tips for utilizing console log within a react form component

I'm currently exploring ways to communicate with a React form in order to provide it with an object.id for updating purposes. While I can successfully console log the object.id within the update button and modal, I am struggling to confirm if the val ...

Choosing various files from separate directories within an HTML input type="file" element

Is there a way to select multiple files from various directories using the HTML input type="file" element? I have been searching for resources on how to do this without any luck. Are there any npm packages that can assist with achieving this functionalit ...

Is there a way to verify the availability of an authenticated resource without triggering a pop-up for credentials in the browser?

I am facing the challenge of fetching data from a web service located on a different server without knowing if the user has an active session on that server. If the user does have a session, I want to retrieve the data automatically. However, if they do no ...

Several adhesive panels on a dynamic webpage

In the content area of my page, a dynamic number of rows are generated. Each row consists of two columns: a side block and a content area. The goal is to have the side block stick while the page scrolls down until the next block appears and pushes the prev ...

problem with increasing/decreasing buttons in a react application

My goal is to display a list of Names in a specific order, but I'm encountering an issue when using the increment and decrement buttons. When I click the increment button, the order increases by 1 as expected. However, when I click the decrement butto ...

What is the minimum required node.js version for my project to run?

Is there a command in NPM that can display the minimum required Node version based on the project's modules? ...

the JavaScript anchor feature is malfunctioning

Steps to Play Back: To start, in the header section, select any of the links with anchors: ##bankaccount #pack #platform #acq ##scorecard ##intrade #form Next, scroll up to the top of the page Then, reload the page Actual Outcome: Upon reloading a page w ...

Dealing with the response data from $http request in AngularJS

Below is the client-side code written in AngularJS (which is functioning properly): $scope.ajaxLogin = function(){ var fn = document.getElementById("username").value; var pw = document.getElementById("password").value; $http({ url: "my ...