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

express-validator: bypass additional validation in a user-defined validator

Utilizing the express-validator package for validating my request data. As per the documentation, we need to declare them in this manner: app.use(expressValidator({ customValidators: { isArray: function(value) { return Array.isArray(value); ...

Submitting the Ajax form will result in the quantity of the product in the cart being updated while remaining on

Hello, I am using ajax to keep the user on the same page after submitting a form. If successful, I will use ajax load to load another page that displays the quantity of the product. However, I am facing an issue where each subsequent submit increases the q ...

Stagnant variable value after onClick event

After exploring various solutions, none seem to quite fit my needs. I want to update the variable "currentIndex" when a user clicks on an image. Currently, the change occurs within the onClick function but does not affect the outside variable. I am unsur ...

Exploring the nuances in semantics between AJAX and post/get requests

I'm currently trying to grasp the concept of 'AJAX.' I know that it is short for Async JavaScript over XML, although JSON can also be used instead of XML. As far as I understand, AJAX allows for updating only parts of a web page without need ...

Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have: 0: {name: "Jan", value: 12} 1: {name: "Mar", value: 14} 2: {name: "Feb", value: 11} 3: {name: "Apr", value: 10} 4: {name: "May", value: 14} 5: {name: "Jun", value ...

Scraping JavaScript Content Webpages with VBA

I'm attempting to extract a table from the Drainage Services Department website. I've written the VBA code below, but it doesn't seem to be working. I suspect that the issue lies in the fact that this particular table is generated using Java ...

Setting Start and End Dates in Bootstrap Vue Datepicker to Ensure End Date is After Start Date

My Vue.js form includes two BootstrapVue datepickers for holiday management. Users can define the start date and end date of their holiday, with the condition that the end date must be equal to or greater than the start date. Here is my current implementat ...

Determining the Area of a Polygon Based on its Slope or Angle

Is it possible to calculate the area of a polygon when it has an inclination or slope? I have both the angle/slope and the points of the polygon, and I need to determine the area. How can this be achieved? ...

implementing one active line item at a time in Vue

Within my Vue template, I have a small unordered list: <ul style="border-bottom:none !important; text-decoration:none"> <li class="commentToggle" v-bind:class="{active:commentActive}" v-on:click="setInputName('new')">New Comment ...

What could be the reason behind ng-bind-html only displaying text and not the link?

Utilizing ng-repeat to exhibit a list on my webpage. One of the fields in my data contains a URL that I want to display as an actual link within my HTML page. Please refer to the screenshots below: My HTML: My rendered page: I have included the angular- ...

Troubleshooting a Laravel 5.2 modal popup issue for password recovery, experiencing a 500 internal server error with the Ajax function execution

Is there a way to check if an email exists in order to send a reset password link using an AJAX function? I keep encountering a 500 internal server error before the AJAX runs. I understand that a 500 error is usually due to a token mismatch, but do I actua ...

Is there a way to incorporate a component into Particle.js?

I attempted to encase the Particle around the component but it's not functioning correctly import React from "react"; import { render } from "react-dom"; import Particles from "./Particles"; import "./index.css" ...

Utilizing JQuery to select list items for pagination purposes

I am currently working on a pagination script and everything seems to be functioning well, except for one minor issue. I am struggling with triggering an action when the page number (li) is clicked. The pagination data is being retrieved via ajax and disp ...

Changing the content of a form with a personalized message

I am currently working on a Feedback modal that includes a simple form with fields for Name, rating, and comment. After the user submits the form, I intend to display a custom message such as "Your feedback has been submitted." However, I am facing an issu ...

How to retrieve the correct instance of "this" from a callback function within an array of functions nested inside an object

Trying to access the "helperFunction" from within a function in the "steps" array has been quite challenging. It seems that using "this" does not point to the correct object, and I have been struggling to find the right solution. const bannerAnimation = { ...

Multer is experiencing difficulties in uploading files, yet it is not displaying any error messages

When setting up an application to create courses with images, I encountered an issue while using multer for image uploading. Despite adding multer to my route with upload.single('images'), the uploaded images were not appearing in the designated ...

What steps should I take to verify the validity of an Angular form?

I am struggling with validating an inscription form in HTML. Despite trying to implement validations, the inputs are still being saved in the database even when they are empty. Here are the validations I want to include: All inputs are required Email addr ...

Angular 7 error: No provider found for PagerService causing NullInjectorError

I have been struggling to get pagination working properly in my project. Below is the code I have written: pager.service.ts: import * as _ from 'underscore'; @Injectable({ providedIn: 'root', }) export class PagerService { ...

Is it true that by utilizing Vue's v-for, every line of HTML code becomes a

I'm struggling to utilize v-for in order to create multiple div elements, but no matter how I attempt it (even trying to iterate over a list), the v-for doesn't seem to function properly and always turns the line into a comment when executed. No ...

Every time I navigate to a new page in NextJs, the useEffect hook

I am working on developing a new blog app with Next.js. In the current layout of the blog, I have successfully fetched data for my sidebar (to display "recent posts") using the useEffect/fetch method, as getInitialProps only works on Pages. However, this ...