I'm having some trouble with this search filter in Vue 2 - is it failing to display the items as expected

After struggling with this issue for over a week, I've hit a roadblock and need some assistance.

I'm currently working on implementing a search filter in Vue 2 with Vuetify, but something isn't quite right.

Here's a snippet of the search filter code:

  <v-text-field v-model="search" label="Look for name..."></v-text-field>

I have a two-way binding variable called 'search' in the component data for the text-field v-model.

Additionally, I have an array of items:

items: [
  {
    default: true,
    name: 'Text 1',
  },
  {
    default: false,
    name: 'Text 2',
  },
  {
    default: false,
    name: 'Text 3',
  },
  {
    default: false,
    name: 'Text 4',
  },
],

I'm rendering the list in a div using v-for:

<div v-for="(item, index) in filteredItems">
    <div style="display: flex">
      <input
        type="radio"
        :checked="item.default"
        @click="changeDefault(item, index)"
      />
      <h1>{{ item.name }}</h1>
    </div>
  </div>

This is how the component appears: View the rendered list and search filter

Wondering how the filter works? Check out the code snippet below:

filteredItems() {
  if (this.search) {
    return this.items.filter((item) => {
      return item.name.toLowerCase().match(this.search);
    });
  } else {
    return this.items;
  }
},

Everything seems to be functioning properly, but there's an issue when I search for an item (e.g., 'Text 2') and click the radio button. Upon clearing the filter, it seems like nothing has changed.

It only happens when using the search method; clicking an item in the initial list changes the radio button as expected. View 'Text 2' search View after clearing the search

It appears that the list isn't rendering the new items properly. I'm really stuck here and would appreciate any help!

<template>
  <v-app>
    <v-main>
      <v-text-field v-model="search" label="Look for name..."></v-text-field>
      <div v-for="(item, index) in filteredItems">
        <div style="display: flex">
          <input
            type="radio"
            :checked="item.default"
            @click="changeDefault(item, index)"
          />
          <h1>{{ item.name }}</h1>
        </div>
      </div>
    </v-main>
  </v-app>
</template>

<script>
export default {
  name: 'App',

  components: {},

  data: () => ({
    search: '',

    items: [
      {
        default: true,
        name: 'Text 1',
      },
      {
        default: false,
        name: 'Text 2',
      },
      {
        default: false,
        name: 'Text 3',
      },
      {
        default: false,
        name: 'Text 4',
      },
    ],
  }),
  methods: {
    changeDefault(item, index) {
      console.log(item);
      let indexOfDefaultTrue = this.items.findIndex((item) => item.default === true);
      console.log(indexOfDefaultTrue);
      this.items[indexOfDefaultTrue].default = false;
      this.items[index].default = true;
      console.log(this.items);
    },
  },
  computed: {
    filteredItems() {
      if (this.search) {
        return this.items.filter((item) => {
          return item.name.toLowerCase().match(this.search);
        });
      } else {
        return this.items;
      }
    },
  },
};
</script>

Answer №1

It appears that 'filteredItems' might not be behaving reactively. Could it possibly be a computed function? It seems that it's not updating whenever 'this.search' changes.

If you could provide a more extensive snippet of the code, I'd be happy to investigate further.

Answer №2

Here is the full answer:

The issue with the code lies in the usage of the item index in the 'changeDefault' function. It is recommended to use the item name instead of the index as the index is dynamic. For example, when searching for 'Text 2', the index used should be 0, not 1:

function changeDefault(clickedItem) {
  
      let indexOfDefaultTrue   = items.findIndex((item) => item.default === true);
      let indexOfbuttonClicked = items.findIndex((item) => item.name === clickedItem.name);

      items[indexOfDefaultTrue].default = false;
      items[indexOfbuttonClicked].default = true;

    }

Also, make sure to update the input radio accordingly:

   <input
            type="radio"
            :checked="item.default"
            @click="changeDefault(item)"
          />

For more information on the code, you can check out the link provided: Click here for more details

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 enhance the class following this condition in JavaScript?

Initially, the original script worked perfectly with just one class being added: function check_btn_charge() { if (parseInt(jQuery(".total-change-price").text()) >= 0) { jQuery(".btn-action-save-charge"+"&nbsp;"+"btn-danger" ...

What is the best way to include a string in an Ajax GET request as a query parameter without it being encoded?

I've encountered an issue while trying to pass a list of subject IDs as query params in an Ajax get-request. The API expects the subjectId param to be either a single number or a string of numbers separated by commas. I have made sure that what I am s ...

Convert a Material UI component into a string representation

I've been tasked with using a tool that creates a terminal interface within the browser. Our goal is to display HTML content, including Material components. The tricky part is that the tool requires input as strings. I discovered a package called jsx- ...

Utilizing vue-router to create two separate navigation bars where only one link is highlighted as active

In my setup, I have implemented two sections with navigation structured as follows: <ul class="navigation-list"> <li v-for="(route, index) in navRoutes"> <router-link :to="route.path"> <span>{{ route.name }}</span> ...

What is the best way to efficiently set up a scrolling text ticker for repeated use?

I am currently utilizing GreenSock/TweenMax for the creation of scrolling text, inspired by the design seen on this webpage: If you're interested in learning more about Greensock and its capabilities, take a look at their documentation here: While I ...

JavaScript classList.remove function experiencing inconsistencies

Take a look at this fiddle: JSFiddle The HTML code: <table class="myTable"> <tr> <th>Some text</th> <td class="align"> <span class=" someStyle">1</span>/<span class="otherStyle">15</span& ...

Utilizing a While Loop for SQL Queries in a Node.js Environment

So, I was attempting to iterate through an array using a while loop. I was able to successfully print a result from the SQL connection without the while loop, confirming that the query is working. However, when I tried to implement the same query within a ...

Changing date and time into milliseconds within AngularJS

Today's date is: var timeFormat = 'dd MMM, yyyy hh:mm:ss a'; var todayDate = dateFormat(new Date(), timeFormat); Can we convert today's date to milliseconds using AngularJS? Alternatively, how can we use the JavaScript function getT ...

When utilizing a React styled component, it functions smoothly during development but triggers a build error when in production

Recently, I encountered a strange issue with my code. I have a styled component div that wraps around another component in this manner: <ContentWidget> <BookDay /> </ContentWidget> (The Bookday component returns an empty div so there ...

"Step-by-step guide on deactivating SmartyStreets/LiveAddress with an onclick function

I've recently taken over a SquirrelCart shopping cart application that utilizes SmartyStreets/LiveAddress code, and I'm struggling to figure out how to disable the verification process when copying billing address fields to shipping address field ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

Issue with dynamically added inputs rendering Jquery Masked Input ineffective

Currently facing a challenge while creating a signup form for a project. The issue lies in the functionality of my form which allows users to click an "add contact" button to dynamically generate more input boxes on the page for entering additional user in ...

Modifying the color of a specific div using jQuery

I am attempting to develop a function that changes the background color of a div when a user clicks on it and then clicks on a button. The value needs to be saved as a variable, but I'm having trouble getting it to work because it keeps saying that th ...

Is it necessary to configure modules using app.use in every route in express.js?

I recently learned that it is best practice to include the express module individually in each route file, rather than globally in app.js. Now I'm questioning whether I need to duplicate all the app.use statements in each route file or if I can just ...

The CSS style class is applied to two menus that share the same route but have different query parameters. These menus are styled with the class name

Utilizing both Vue and Vuetify version 3. For my navigation, I have implemented the v-navigation-drawer component alongside v-list for each menu item: <template> <v-navigation-drawer> <v-list nav> <v-list-item title=" ...

What should I do to resolve the "Too few arguments to function" issue in Laravel when using VueJS and implementing DOMPDF?

I'm currently developing an application for a Lab using Laravel and VueJS, where I need to generate PDF reports. To achieve this, I have installed DOMPDF. However, when attempting to execute the method in VueJS to open the PDF, I encounter the follow ...

What is the best way to encapsulate multiple Bluebird promises within a single promise?

Seeking assistance in creating an async wrapper for a redis query supported by a db query. If the redis query fails, I want to execute the db query instead. When the db query is successful, I aim to store the returned data in redis before sending it back. ...

Issue encountered when attempting to invoke a service from an Angular component within an office.js dialog

Our application utilizes Angular 5 and integrates Office.js to interact with Microsoft Office Word documents. Step 1: We use office displayDialogAsync to load the component. https://i.sstatic.net/uhT66.png Step 2: Inside the attribute-users component, an ...

A Nuxt plugin that integrates a separate website into the serverMiddleware

The concept Imagine having a main Nuxt website just like any other. Now, think about adding my module to your project. This module will then introduce a subdomain "admin.example.com" to your project, creating a fully functional Nuxt-based website that ope ...

Steps for retrieving a Unicode string from PHP using AJAX

In order to retrieve Unicode strings from PHP for my project, I figured that using AJAX would be the most suitable method. $.ajax({ url: './php_page.php', data: 'action=get_sum_of_records&code='+code, ...