Browsing a Table in Vue

I'm currently building a Vue application that showcases a collection of quotes and includes a search feature for filtering through the data. It seems like I might not have properly linked the function to the correct element. I've added a v-model attribute to the input tag, which should bind the user-entered text.

Take a look at my template:

<template>
  <div class="container">
    <h3>Quotes</h3>
    <div class="controllers">
      <div class="search">
         <input id="search-item" type="text" placeholder="Search for a quote..." v-model="searchText"/>
         <button @click="searchResults()" class="search-btn">Search</button>
      </div>
    </div>
    <table class="table">
      <thead>
        <tr>
          <th scope="col">Source</th>
          <th scope="col">Context</th>
          <th scope="col">Quote</th>
          <th scope="col">Theme</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="quote in quotes" v-bind:key="quote.quote"> 
          <th scope="row">{{quote.context}}</th>
          <td>{{quote.source}}</td>
          <td>{{quote.quote}}</td>
          <td>{{quote.theme}}</td>
        </tr>
      </tbody>
    </table> 
  </div> 
</template>

Here's my script:

  import axios from 'axios';
  export default {
    name: 'Quotes',
    data() {
      return {
        searchText: '',
        quotes: [ 
          {
            quote: null,
            context:  null,
            source: null,
            theme: null,
            currentPage: 0,
        }
        ],
      };
    },
    mounted() {
      axios
        .get('https://gist.githubusercontent.com/benchprep/dffc3bffa9704626aa8832a3b4de5b27/raw/quotes.json')
        .then(res => {
          this.quotes = res.data;
        })
      },
    methods: {
      searchResults() {
        if (this.searchText.length === 0) {
        return '';
      }
      return this.quotes.filter(quote => quote.quote.match(this.searchText));
     },
  }
}

Despite no compiler errors, the search functionality doesn't seem to be working as expected when implemented.

Answer №1

Your approach seems to be incorrect. Here is a revised version of the method:

    searchResults() {
        if (this.searchText.length == 0 || this.searchText == '') return;
        this.quotes = this.quotes.filter(quote => quote.quote.match(this.searchText));
    }

Instead of using return this.quotes, it is recommended to modify the array directly. However, this can lead to emptying the array, so it is advisable to use another variable to store the original array.

Consider the following improved version:

    import axios from 'axios';
    export default {
        data() {
            return {
                searchText: "",
                quotes: [],
                data: [],
            };
        },
        mounted() {
            this.fetchQuotes();
        },
        methods: {
            fetchQuotes() {
                let url = 'https://gist.githubusercontent.com/benchprep/dffc3bffa9704626aa8832a3b4de5b27/raw/quotes.json/';
                axios.get(url).then(res => {
                    this.quotes = res.data;
                    this.data = res.data;
                });
            },
            searchResults() {
                if (this.searchText.length == 0 || this.searchText == '') {
                    this.quotes = this.data;
                }
                this.quotes = this.data.filter(quote => quote.quote.includes(this.searchText));
            }
        }
    }

Answer №2

There seems to be an issue with the searchResults() function because it is only filtering this.quotes and returning this value without actually using it, causing the object this.quotes to retain its original values. To address this, it is recommended to update the this.quotes when calling the searchResults() function, while also remembering to store the initial results.

A more effective approach would be to utilize a computed variable that filters this.quotes as needed. You can find more information on computed properties at https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties

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

Unraveling complex JSON structures in Node.js

I've been working on parsing nested JSON data and here is the code I'm currently using var str = '{"key1": "value", "key2": "value1", "Key3": {"key31":"value 31"}}'; v ...

Troubleshooting the malfunction of jQuery's change() function

There are three HTML select tags on my page. I want these three select tags to function as follows: When I change selectA, selectB should automatically update based on the selection in selectA. Similarly, when an option in selectB is created, changing se ...

What is the best method for retrieving the selected itemsPerPage in Vuetify's data-table in version 2.0

Recently, I've been struggling to retrieve the selected items-per-page on a Vuetify data-table due to some recent changes. I came across this helpful example: How to set initial 'rows per page' value in Vuetify DataTable component? Here is th ...

Why is Node.js unable to locate my files?

I'm currently utilizing Node.js as my server, and I'm encountering some difficulties in serving my JS and CSS files. For some reason, index.html is unable to locate them. Whenever I try to load up my browser, I encounter the following error: htt ...

"Exploring the functionality of Vue JS2 checkboxes within a parent and

I am working with a complex nested list structure: <ul> <li v-for="subregion in continents"> <input type="checkbox" :id="subregion[0].subregion" > <label :for="subregion[0].subregion">{{ subregion[0].subregion }}< ...

Modify the row's background color after clicking the delete button with jquery

Greetings, I am facing an issue with changing the color of a row in a table when clicking on a delete button. Despite trying various methods, I have not been successful. How can I modify the ConfirmBox() method to change the row's color? Your assistan ...

Adding static JSON array data to the results received from an API call

Within my code snippet below, I am able to retrieve a JSON Response: respArray = [] respArray = respBody.classifiers respBody = respArray if (respBody.length > 0) { respBody = applyPagination(respBody, reqParams.filter, option ...

Determine the optimal number of units to purchase with a given budget

Looking to automate a procurement process with my new agent: let perunitcost = 100; let agentMaxQty = 60 let agentMaxTotal = 5000 let qtyToBePurchased = 0 The agent has a budget limit of $5000 and can procure up to 60 items. In this scenario, the agent w ...

Ways to enhance a Vue component using slots

I am looking to enhance a third-party library component by adding an extra element and using it in the same way as before. For example: <third-party foo="bar" john="doe" propsFromOriginalLibrary="prop"> <template v ...

Ensure that the CSS fade-in effect occurs every time the element is clicked, not just the first time

Is it possible to make text fade in on every click instead of just the first time by using CSS transitions and JavaScript? My current progress: <style> #data { transition: .7s; } </style> <h1 id="data"></h1> <a hr ...

What is the best way to incorporate npm packages and ES6 features into Django?

As I work on the frontend development of my Django application, I am keen on incorporating the official material design components. Yet, I am faced with a challenge in seamlessly integrating these components. I am looking for a way to import the npm packa ...

Tips for setting an identification value within mongodb?

Currently, my focus is on utilizing node.js and mongoose. I am in the process of developing a REST API to showcase my User model: var userSchema = new Schema({ _id: {type:Number}, username: {type:String}, age: {type:Number}, genre:{type: Number,ref:&a ...

The functionality of passing an ID in Bootstrap Modal is not functioning as expected

I'm facing an issue with passing an ID to my modal. My goal is to have the details of an event displayed in the modal when the corresponding link (which represents the event) is clicked. However, I'm struggling to retrieve the ID and show the ev ...

When the draggable item is released near the drop zone, allow drag and drop to combine

In my latest project, I created a fun game that involves matching different shapes. The goal is to drag the correct figure next to its corresponding shadow figure for a perfect match. Currently, if you partially overlap the square with its shadow, the game ...

Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated. The current representation of individual's data ne ...

How can we achieve the same functionality as React Native's { flex: 1 } in React JS?

I've been diving into React Native development, and now I'm exploring React.js for web applications. However, I'm facing a challenge in creating a simple View that takes up the entire screen to begin experimenting with different components. ...

Display a PDF file within an IFrame using JavaScript and then print it

Why is it so challenging to achieve? I've dedicated 48 hours to research this, yet it seems impossible! Although recent Chrome versions allow the parent window to access PDFs in iframes, both FF and IE prevent any interaction with the iframe that dis ...

What purpose does the question mark (?) serve after a class name when invoking class methods in TypeScript?

One interesting element within my TypeScript code snippet is the presence of the statement row?.delete();. I'm curious about the significance of the question mark in this context. What would be the outcome if 'row' happened to be null? Ap ...

Angular 2 TypeScript: The concat() function operates as mutable within the framework

When I declare an array on an @Injectable provider, my intention is to use it across different components. normeList: any[] = [ { name: 'choice 1', type:'false' }, { name: 'choice 2', typ ...

Is there a way to modify the "loadOnDemandItemTemplate" for RadListView in NativeScript-Vue?

After going through the Radlistview documentation at RadListView Load on Demand, I am still unsure how to customize the "loadOnDemandItemTemplate" in NativeScript-Vue. The current template includes "Load More" and "Loading" labels by default. <RadList ...