Utilizing Vue.js to apply conditional statements or filters on v-for generated outputs

Currently, I am working on organizing my results by category. I believe there is room for improvement in the way it's being done:

<div><h2>Gloves</h2></div>
<div v-for="stash in stashes" :key="stash.id">
  <div v-for="item in stash.items" :key="item.id">
    <div v-if="item.extended.subcategories[0] === 'gloves'">
      {{ item.extended.baseType }}
    </div>
  </div>
</div>
<div><h2>Boots</h2></div>
<div v-for="stash in stashes" :key="stash.id2">
  <div v-for="item in stash.items" :key="item.id2">
    <div v-if="item.extended.subcategories[0] === 'belt'">
      {{ item.extended.baseType }}
    </div>
  </div>
</div>
..

I came across this article that explains using a computed property to achieve what I want, but I'm having trouble making it work (I think because it requires an argument):

  computed: {
    filter(category) {
      return this.stashes.items.filter(a => a.extended.subcategories[0] === category);
    }
  }

and then something like this:

<div v-for="item in filter('gloves')" :key="item.id">
 ..
</div>

However, I found that passing an argument in the loop as shown above isn't allowed, and I'm stuck at this point.

Does anyone have any suggestions on how to approach this issue?

This is how the "stashes" data structure looks:

stashes: [
  {
    id: 1,
    items: [{
      name: 'lorem',
      extended: {
        subcategories: ["gloves"]
      }
    }]
  },
  {
    id: 2,
    items: [{
      name: 'ipsum',
      extended: {
        subcategories: ["boots"]
      }
    }]
  },
]

Answer №1

One way to address this issue is by introducing an additional level of iteration through a nested v-for loop in the template:

<div v-for="category in categories" :key="category">
  <div><h2>{{ category }}</h2></div>
  <div v-for="stash in stashes" :key="stash.id">
    <div v-for="item in stash.items" :key="item.id">
      <div v-if="item.extended.subcategories[0] === category">
        {{ item.extended.baseType }}
      </div>
    </div>
  </div>
</div>

Furthermore, you can create an array of categories within your data method like so:

data() {
   return {
      categories: ['helmets','boots']
   }
}

Answer №2

To achieve this functionality, one option is to return a method from your computed property. However, I do not recommend this approach. It would be better to use a regular method instead of a computed property.

[RECOMMENDED]

method: {
    filter(category) {
      return this.stashes.items.filter(a => a.extended.subcategories[0] === category);
    }
  }

[USING COMPUTED]

computed: {
    filter() {
      return category => this.stashes.items.filter(a => a.extended.subcategories[0] === category);
    }
  }

For more information on this topic, you can refer to the following discussion: Why can't parameters be passed to computed properties in Vue.js?

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

Using JSTL within JavaScript

Can JavaScript be used with JSTL? I am attempting to set <c:set var="abc" value="yes"/> and then later retrieve this value in HTML and execute some code. The issue I'm facing is that the c:set always executes even when the JavaScript condition ...

Tips for troubleshooting ImageArray loading issues in AngularJS

Having some trouble learning Angular and getting stuck with this Image array. Can someone please help me understand what's wrong with my code and how to fix it? FilterAndImages.html <!DOCTYPE html> <html ng-app="store"> <head> < ...

What is the best way to mix up all the characters within the content of an HTML document?

<div id="contentContainer"> <h1>First Page</h1> <section id="mainSection"> <p>Lorem ipsum dolor sit amet</p> <ul> <li><a href="#">Black world</a></li> ...

What is the best way to incorporate a URL into your routes?

Within my 10 arrays, each character holds valuable information. My goal is to create a navigation feature that allows me to click on a character and access their specific array data. I am faced with a dilemma regarding dynamic routing - should I extract th ...

How can you use Knex to order the results for each WHERE clause in a SELECT query?

When querying a database using knex, the desired results should be ordered in a specific manner. The current code provides the required results but lacks the expected order. knex("FRUITTBL") .select("FruitTag", "FruitName", ...

Unexpected outcomes arising from using nested arrays with jQuery validation plugin

I have been utilizing the jQuery validation plugin from . I am encountering an issue with validating a nested array "tax_percents[]" that is within another array. The validation seems to only work for the first value in the array, and even for the second f ...

Utilize Twilio to forward messages to a different phone number

I am seeking a solution to automatically forward incoming messages from one Twilio number to another, based on the original sender's number. For example: If I receive a message on my Twilio number "+14444444444" from '+15555555555', I want ...

Performing numerous asynchronous MongoDB queries in Node.js

Is there a better way to write multiple queries in succession? For example: Space.findOne({ _id: id }, function(err, space) { User.findOne({ user_id: userid }, function(err, user) { res.json({ space: space, user: user}); }); }); It can g ...

The issue of AJAX .done() method returning undefined when using $.each() on JSON response

I am having trouble retrieving the JSON response from an $.ajax() request. After selecting a car model, I receive data from the API, but I am unable to access the JSON results to populate a new drop-down list with the required information. HTML <div cl ...

When I try to set a property for the drawer to dispatch the toggleDrawer action in Vue, the page fails to

One of my Vue components, Sidebar, includes a navigation drawer created with Vuetify. The drawer's state is managed using v-model, with the state itself stored in Vuex to allow other components to modify it. However, when I define a setter for the com ...

"The text() or json() methods in Javascript's fetch function never seem to resolve, leaving the operation in a perpetual

In my new nextjs 13 project, I'm attempting to perform a fetch operation (unsure if it's related to JavaScript or nextjs) and using console.logs to monitor the code execution. let url = `${BASE}/${module}/${path}`; url += "?" + ne ...

Display different images based on user selection in vue.js

I am new to working with vue.js and I'm facing a challenge. My goal is to display images of NBA players based on the selected criteria using vue.js. For instance, if the Dunk contest champion is chosen, only images of Kobe and Jordan should be display ...

What steps can be taken to create a build that organizes files into separate folders based on their file types?

Can someone assist me with Vite? How can I create a build that organizes files by their type into separate folders? The desired output should look like this: /dist /styles/*.css /scripts/*.js /images/[*.png|*.jpg|*.gif] index.html ...

Vue.js - The prop "src" is invalid as the type check has failed. The expected type should be either a string or an object, but a

I am currently working on integrating an image into my Firebase's Firestore and Storage, and then displaying it on a v-card component. Here is the code for my v-card: <v-row> <v-col cols="3" v-for="massage in massages" ...

What is the best method to divide a string, enclose it within a span tag, and generate fresh code using jQuery?

Is there a way to separate multiple links, enclose them in a span tag, and then iterate through them to display them back within the a tag? I have managed to split all the dates into the dateArr array, but I need help looping through them to output each on ...

Attempting to render a container within a hidden div and then make it visible results in an error

There appears to be an issue with ExtJS 6 regarding a bug. The problem can be replicated with minimal code in this online demo. In the code snippet below, we have a hidden div: <div id="btn"></div> <div style="display:none" id="outer_contai ...

Choose options with selectize.js including option separators

My list of countries includes options with dashes as separators, but when I use selectize they disappear. How can I visually separate items in the list without using labelled option groups? <select class="form-control" id="Country" name="Country"> ...

How can I dictate the placement of a nested Material UI select within a popper in the DOM?

Having trouble placing a select menu in a Popper. The issue is that the nested select menu wants to mount the popup as a sibling on the body rather than a child of the popper, causing the clickaway event to fire unexpectedly. Here's the code snippet f ...

Should I opt for using mounted or created?

While working with VUE, I encountered an issue where I needed to pass an ID from a parent component to a child component. However, I noticed that when the child component is called again through a button after the initial render, the ID becomes null. Shoul ...

Maximizing the efficiency of this JavaScript code

Is there a way to optimize this code for better efficiency? I'm trying to enhance my coding skills and would appreciate some feedback on this particular section: $(function(){ $('#buscar').focus(function(){ if(($(this).val() === ...