What is the process for implementing a title search filter in Vue.js?

Hey there, hoping you're having a good night! I've been trying to set up a bookstore using Vue.js with code retrieved from a Json api. However, I'm encountering some issues with the "computed" property. Here's the code snippet:

new Vue({
  el: "#vue-app",
  data() {
    return {
      title: "Ubiqum Bookstore",
      books: []
    }
  },
  mounted() {
    this.getAPI('https://api.myjson.com/bins/1h3vb3');
  },
  methods: {
    getAPI() {
      axios.get('https://api.myjson.com/bins/1h3vb3')
        .then(response => {
          (this.books = response.data.books)
        })
        .catch(e => {
          console.log("No found!")
        })
    }
  },
  computed: {
    booksFilter: function() {
      var textSearch = this.textSearch;
      return this.books.filter(function(el) {
        return el.books.toLowerCase().indexOf(textSearch.toLowerCase()) !== -1;
      });
    }
  },
})

I'm puzzled about why the computed property isn't functioning as expected. In my HTML, I have:

<div id="list-countries" v-if="booksFilter && booksFilter.length">
    <div class="panel panel-default" v-for="book of booksFilter">
<input id="input-search" type="text" class="form-control" v-model="search" placeholder='Search...'>

If you have any insights or solutions to this issue, I'd greatly appreciate it! Thank you very much!

Answer №1

To clarify, the variable this.searchText mentioned in a comment should be replaced with search in the template. Since your array consists of objects, you may want to filter by a specific attribute (such as titulo as suggested in another answer). One approach is to use includes() to determine if the input value matches the attribute you are searching for (e.g. titulo). Here is a revised solution:

data() {
  return {
    title: "Ubiqum Bookstore",
    books: [],
    search: '' // Ensure to include this property!
  }
},
// .....
computed: {
  booksFilter: function() {
    return this.books.filter(book => {
      return book.titulo.toLowerCase().includes(this.search.toLowerCase());
    });
  }
}

Update your template to:

<div v-if="booksFilter && booksFilter.length">
  <div v-for="book of booksFilter">
    <p>{{book.titulo}}</p>
  </div>
</div>

Click here for a SANDBOX to experiment with the code.

Answer №2

There are multiple errors in your code that need to be addressed:

computed: {
    booksFilter: function() {
        var textSearch = this.textSearch; // The variable textSearch does not exist in the data or v-model, so it likely contains invalid data
        return this.books.filter(function(el) {
            // In the line below, el.books is not a valid property. If you want to match with the title, change it to el.titulo
            return el.books.toLowerCase().indexOf(textSearch.toLowerCase()) !== -1;
        });
    }
}

Additionally, if you want to use the title value from the data model, you will need to adjust the computed property like this:

computed: {
    booksFilter: function() {
        return this.books.filter(el => {
            return el.titulo.toLowerCase().indexOf(this.title.toLowerCase()) !== -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

Close session when browser/tab is exited

After extensive searching online, I have been unable to find a satisfactory solution for ending a session when a browser or tab is closed without requiring the user to log off. I have attempted numerous JavaScript codes that I came across, but none of the ...

How to implement hover effect to show child div within parent div using React.js

Hey there! I'm fairly new to working with react js and currently trying to add some animation to a nested div. The parent div, known as " portfolio-product-item ", showcases a featured image pulled from the WP REST API. Inside this parent div, there&a ...

JQuery Script Perform an Action - Pause - Execute Another Action

I'm working on a function that involves running some jQuery code, pausing for around 5 seconds, and then executing something else. Here's an example of what I'm trying to achieve: function myFunc() { var str1 = 'This is the starti ...

Tips for uploading a jpg image to the server using react-camera

My objective is to transfer an image captured from a webcam to a Lambda function, which will then upload it to AWS S3. The Lambda function appears to work during testing, but I'm struggling to determine the exact data that needs to be passed from the ...

Unable to access res.name due to subscription in Angular

Right now, I am following a tutorial on YouTube that covers authentication with Angular. However, I have hit a roadblock: The code provided in the tutorial is not working for me because of the use of subscribe(), which is resulting in the following messag ...

The gauge created dynamically using the justgage plugin does not display the value

I am currently experimenting with dynamically adding gauges, and although they are displayed on the screen, the values being shown are incorrect. Even when the graph indicates a different value, it still displays 0. These gauges are triggered by an onclick ...

Using more than one class at a time is causing issues

Essentially, I have a div and I want to create an exercise where I apply three different classes using vue.js. I attempted to use v-bind:class, specifically :class, but can I bind a class directly from CSS? This is what I tried: html <div :style="[my ...

Basic Vue application displays only empty screens (using webpack-dev-server)

I recently started developing my first Vue app, and everything was going smoothly until I added some routes. Now, I'm facing an issue where no output is displayed in the browser. Previously, I could see a simple static string before implementing routi ...

Error encountered while executing jest tests due to an unexpected import token

Despite trying numerous solutions and suggestions on Stack Overflow, I am still unable to resolve the issue at hand. I recently discovered jest and attempted to use it by following a tutorial on testing React components with jest from DZone. However, when ...

Determine if the input number exceeds a specified threshold by implementing JavaScript

My attempt at performing calculations on a page is not yielding the desired results. I have tinkered with the code below, but it doesn't seem to be working as expected. Can anyone provide guidance on where I might be going wrong? Specifically, I want ...

Ways to verify if a value already exists in a pre-existing JSON file using Node.js

On the backend side, I have a json file containing addresses. From the client side, I am receiving a user's address through an API post method. My goal is to verify if the address provided by the user already exists in the JSON file. The addresses in ...

Tips on ensuring the <script> section of a Vuejs single file component loads prior to the <template> section

After posing my query here, I have come to the realization that the root of my problem might be due to the template loading before the script. This causes an error when it encounters an undefined variable, halting the script execution. The issue could pote ...

Comparison of Vue 3 Composition API - watchEffect and watch

I've recently been delving into the world of Vue Composition API and have found myself pondering about the distinctions between watchEffect and watch. The documentation implies that watch functions similarly to the Vue 2 watch, leading me to speculate ...

Having trouble getting the innerHTML update to be triggered by onchange

Hey there, I am looking to tweak my file upload button so that it triggers a change in a specific span, signaling to the user that a file has indeed been selected. <script type="text/javascript"> function get_fileName(fileSelector, fileId) { var ...

Saving file with HTML download button results in only HTML document being saved

I am attempting to include a "download file" button on my gatsby website as shown below: <a href="../../images/project-logos/placeholder-company-logo.png" download="test" className="responsive-square project-logo" > <img sr ...

Adjusting the height of a flexbox column to fit three rows within the space of two

Exploring the wonders of Flexbox and delving into its functionality. I have shared a Code Sandbox link showcasing my React /bootstrap code in progress... Currently, I am developing a clock component with two buttons for adjusting time (increase/decrease). ...

send document through ajax

Having some trouble with this task. Here is what I've managed to put together so far: <input id="newFile" type="file"/> <span style="background-color:orange;" onClick="newImage()">HEYTRY</span> I know it's not much progress. ...

Is it possible to integrate a GWT library into Dart programming?

Considering migrating to Dart, but unsure of its maturity. Can a library originally written in GWT be used in Dart? ...

Is it possible to use the Husky "commit-msg" hook to git add new files?

I am currently setting up an automatic versioning system where if I use git commit with the message format PATCH: {message}, the app's patch version will automatically be updated (and the same for the prefixes MINOR and MAJOR as well). My approach inv ...

Ways to show alternative data from a database in Laravel 8

I am working on a project where I need to display additional data based on the option selected from a dropdown menu populated from a database. Can anyone guide me on how to achieve this using javascript or jquery? https://i.stack.imgur.com/k3WLl.png Belo ...