How can you selectively conceal the nth item in a v-for loop while keeping the original array intact? Discover a way to do this using the search function

I have a reference variable called foxArticles that holds a list containing 100 items. Using a v-for loop, I iterate over each value and render all 100 values on the page.

<template>
  <div class="news_container">
    <div
      v-for="article in foxArticles"
      v-bind:key="article"
      class="article_single_cell"
    >
      <div
        class="news_box shadow hover:bg-red-100"
        v-if="containsKeyword(article, keywordInput)"
      >
        <div class="news_box_right">
          <div class="news_headline text-red-500">
            <a :href="article.url" target="_blank">
              {{ article.title }}
            </a>
          </div>
        </div>

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

<script>
const foxArticles = ref([]);
</script>

Additionally, there is a search function in place that checks if an article includes the entered keyword. This function is utilized within the v-for loop.

    <div class="search_input_container">
      <input
        type="text"
        class="search_input"
        v-model="keywordInput"
      />
    </div>

<script>
    const keywordInput = ref("");

function containsKeyword(article, keywordInput) {
  if (article.title.toLowerCase().includes(keywordInput.toLowerCase())) {
    return article;
  }
}
</script>

The challenge arises when attempting to use .slice() on the foxArticles array within the v-for loop, causing issues with the search functionality as it only returns values from the sliced range.

Is there a way to access all values of the array without rendering all 100 articles on the initial load? Any suggestions?

Answer №1

It seems like your method for achieving this could end up being quite complicated. Perhaps a simpler approach would be to always loop through a specific set of data, either based on a search term or the first 100 items.

Since I'm still getting acquainted with the Vue 3 composition API, allow me to show you an example using a regular Vue 2 component.

<template>
   <div class="news_container">
      <div
         v-for="article in matchingArticles"
         v-bind:key="article"
         class="article_single_cell"
       >
            ... news_box ... 
       </div>
   </div>
</template>
<script>
export default {
    ... 
    computed: {
        matchingArticles() {
            var articles = this.foxArticles;
            if (this.keywordInput) {
                  articles = articles.filter(article => {
                      return this.containsKeyword(article, this.keywordInput)
                  })
            } else {
                 // limit the result to 100
                 articles = articles.slice(0, 100);
            }
            // you may want to always limit results to 100 
            // but that choice is yours.
            return articles;
        }
    },

    ....
}
</script>

An added benefit here is that the template itself doesn't have to deal with filtering the results.

Answer №2

Alright, so I've come up with an alternative solution that doesn't require changing the script section...

Instead of using a single v-for loop, you can utilize two separate loops wrapped in v-if statements.

The first v-if statement checks if the search field is empty (keywordInput == ''), and displays articles within a specified range (index, index).

The second v-if statement handles cases where the user has entered a search term (keywordInput != '') and returns relevant articles based on the search query.

<template>
  <div class="news_container">
    <!-- Display articles when no search is performed -->
    <div v-if="keywordInput == ''">
      <div
        v-for="article in foxArticles.slice(0, 4)"
        v-bind:key="article"
        class="article_single_cell"
      >
        <div class="news_box shadow hover:bg-red-100">
          <div class="news_box_right">
            <div class="news_headline text-red-500">
              <a :href="article.url" target="_blank">
                {{ article.title }}
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Display matching articles when a search is performed -->
    <div v-else-if="keywordInput != ''">
      <div
        v-for="article in foxArticles"
        v-bind:key="article"
        class="article_single_cell"
      >
        <div
          class="news_box shadow hover:bg-red-100"
          v-if="containsKeyword(article, keywordInput) && keywordInput != ''"
        >
          <div class="news_box_right">
            <div class="news_headline text-red-500">
              <a :href="article.url" target="_blank">
                {{ article.title }}
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

I'm not certain about the performance implications of this approach, but that's a challenge for another day.

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

Creating a one-of-a-kind entry by adding a number in JavaScript

I am looking for a way to automatically add an incrementing number to filenames in my database if the filename already exists. For example, if I try to add a file with the name DOC and it is already present as DOC-1, then the new filename should be DOC-2. ...

Utilizing vue-socket.io in conjunction with vuex for real-time functionality: A comprehensive guide

I currently have a feed where users can vote on posts. Server > node, express, socket.io v2.3.0 Server > app.js client.on('connection', socket =>{ socket.emit('success', {message: 'Server Accepting Connections' ...

Pre-rendering Vue.js components with dynamically generated PHP content

Seeking guidance on prerendering a Vue app constructed with PHP (either Laravel or pure PHP). My inquiry pertains to understanding how prerendering functions with dynamic content. For instance, when creating a blog using Vue and PHP to display posts, I uti ...

What steps can I take to prompt a ZMQ Router to throw an error when it is occupied?

In my current setup, I have a configuration with REQ -> ROUTER -> [DEALER, DEALER... DEALER]. The REQ acts as a client, the ROUTER serves as a queue, and the DEALER sockets are workers processing data and sending it back to ROUTER for transmission to ...

What is the correct way to define an abstract method within a class to ensure that an IDE detects and notifies if the abstract method is not implemented

Is there a way to properly define an abstract method in an abstract class and have the IDE notify us if we forget to implement it? I attempted the following approach, but it did not work: export abstract class MyAbstractClass { /** * @abstract ...

In the event of a 404 error, simply direct the user to the pageNotFound before ultimately guiding them back

I'm developing a website with Node JS and I want to implement a feature where if the user attempts to navigate to a non-existent page, they are redirected to a "Page Not Found" message before being automatically taken back to the home page after a few ...

Displaying the current time and total time of a custom video player using Javascript

Currently, I'm in the process of creating an html5 video player and have incorporated javascript to update the current time as a fraction of the total time. The script I've written so far is as follows: function updateTime() { var curTime = ...

Retrieve JSON details for various games including their properties

I am currently working on a project that involves accessing Casino Games and their properties from a JSON object to display them on a website. Here is my progress so far: var x = $.getJSON("http://api.bosurl.net/V1/Progressive.asmx/GetProgressiveGames?for ...

Passing a list of objects containing lists in MVC3

Is it possible for me to send an array of objects, each containing arrays, from JavaScript to a MVC action result method? Essentially, I have a KeyValuePair with keys as arrays of strings and I need to return a list of these KeyValuePairs. In my code, I ha ...

Designate categories by utilizing the x-amz-tagging request header

I'm in the process of creating a Node program to upload files to aws s3, and I'm having trouble figuring out how to specify the x-amz-tagging with the request header. I attempted a solution, but it's not working as expected! function crea ...

MongoDB facing difficulties in updating the database

Seeking help with my MongoDB setup as I am still new to it. I have a database where card data is stored and need to update counts when users like cards, resulting in a total likes number. I'm facing an issue where I keep getting a 400 error response ...

How can I correctly implement a pinia store within another pinia store in Vue 3?

Within my todosStore pinia store, I am implementing CRUD operations against the backend. To achieve this functionality, I require a separate pinia store called bannerStore for updating the message and class of the bootstrap alert component in the template. ...

Altering the context of 'this' with the bind method in JavaScript

When using bind to change the scope of 'this', it allows me to reference my generateContent function using 'this' within the click function. However, this adjustment causes the this.id to no longer work due to the changed scope. Is the ...

I want to retrieve a complete HTML page using an AJAX request

I am trying to retrieve the content of a specific page, but encountering issues when using this function: function getResult() { var url="http://service.semanticproxy.com/processurl/ftfu27m3k66dvc3r43bzfneh/html/http://www.smallbiztechnology.c ...

The file module.js is encountering an error at line 327 because it is unable to locate the module named 'express

Hey there, I'm new to nodejs and whenever I run a file in the command prompt like:- C:\demoData>node demo.js I encounter an error like this: module.js:327 throw err; ^ Error: Cannot find module 'express' at Function.M ...

Experience the latest HTML5 features directly within a Java desktop GUI, with seamless communication through

This Java desktop GUI utilizes a Java-based web services communication layer along with an HTML library to provide powerful charting and interactivity. I am looking to integrate an HTML5 view within the Java GUI. Can someone assist me in managing JavaScri ...

How to incorporate template literals when sending JSON responses in Node.js?

Utilizing express and aiming to return some JSON, I am considering using a template literal. Here is my current approach: resp.status(201).json({ message: "Customer added to database", url: "http://localhost:5000/Customer/" + doc._id ...

How do I set the initial state to a specific node in xstate?

I'm currently working on a multi-step form that guides users through selecting services, providing contact information, and entering billing details. I have implemented a progress bar and event emissions to track the user's current step using xst ...

Is there a way to compare two regex values using vuelidate?

Can someone assist me with validating an input field using vuelidate? I am looking to return a valid result if either of the two regular expressions provided below is true. const val1 = helpers.regex('val1', /^\D*7(\D*\d){12}\ ...

Determine the difference between a CSS selector string and an XPath string

Developing a compact querying module (using js) for html is my current project, and I aim to create a versatile query(selector) function that can handle both css selectors and XPath selectors in string form. My dilemma lies in determining whether a given ...