using the information from the child array within a v-if condition

I'm struggling to extract data from a child array and utilize it in my v-if condition.

Below are my data and code. Any assistance would be appreciated, even if it's just pointers to the right documentation.

<div  class='post' v-for="message in messages"  v-if='["Food","Featured"].includes(tag) || tag === ""'>
            
            <h2>{{message.text}}</h2>

            <div v-for="category in message.categories">
              {{category.name}}
            </div> 

</div>

Rather than

v-if='["Food","Featured"]
, I've been attempting
v-if='[category in message.categories]

Clearly, that's not correct. How can I correctly pass data from a nested array UP to the v-if statement?

The data is provided below:

[
   {
      "text":"Featured food content",
      "categories":[
         {
            "name":"Featured",
            "ID": "189"
         },
         {
            "name":"Food",
            "ID": "190"
         }
      ]
   },
   {
      "text":"Featured content",
      "categories":[
         {
            "name":"Featured",
            "ID": "189"
         }
      ]
   }      
]

Thank you for all your help. This is what I came up with until I figure out how to use computed properties properly.

<template v-for="message in messages">
    <div class='post' v-if='message.categories.map(c => c.name).includes(tag) || tag === ""'>
        
        <h2>{{message.text}}</h2>

        <div v-for="category in message.categories">
          {{category.name}}
        </div> 

    </div>
</template>

Answer №1

Important Note: When using v-for and v-if in Vue.js, they should not be combined directly. To make use of v-if, you can convert it into computed properties as shown below:

The variable this.data represents the nested data that has been declared. The filter() method is used to define the test condition.

computed: {
  filteredData: function () {
    return this.data.filter(item => item.categories !== '')
  }
}

You can then proceed with displaying the desired content by iterating through the filtered values:

<div v-for="element in filteredData">{{element}}</div>

Answer №2

If you're looking for a solution, here's one that might meet your needs. Feel free to reach out if you need further assistance. It seems there was some uncertainty about the issue based on the code provided.

<div id="app">
  <div
    v-for="message in messages"
    v-if="messageHasCategory(message, currentCategory)"
  >
    {{message.text}}
  </div>
</div>

const app = new Vue({
  el: "#app",
  data: {
    currentCategory: 'Food',
    messages: [{
      text: 'Food message',
      categories: [{
        name: "Food"
      }]
    }, {
      text: 'Featured message',
      categories: [{
        name: "Featured"
      }]
    }]
  },
  methods: {
    messageHasCategory(message, categoryName) {
      return message.categories.find(c => {
        return c.name == categoryName;
      })
    }
  }
})

Alternatively, you can merge the v-for and v-if into a single computed property as suggested by @zerbene.

<div id="app">
  <div v-for="message in currentCategoryMessages">
    {{message.text}}
  </div>
</div>

const app = new Vue({
  el: "#app",
  data: {
    currentCategory: 'Food',
    messages: [{
      text: 'Food message',
      categories: [{
        name: "Food"
      }]
    }, {
      text: 'Featured message',
      categories: [{
        name: "Featured"
      }]
    }]
  },
  computed: {
    currentCategoryMessages() {
      return this.messages.filter(m => {
        return m.categories.map(c => c.name).includes(this.currentCategory);
      })
    }
  },
})

Check out the Codepen link for a live demo: https://codepen.io/dyllandry-the-styleful/pen/vYKEjeb

Answer №3

(This solution doesn't address the potential conflict of using both v-for and v-if simultaneously, as discussed in detail here: )

To validate category names, you can leverage the .map(...) method on your array. This will generate a new array where you can then use .includes(tag). Insert this condition within your v-if:

tag === "" || message.categories.map(c => c.name).includes(tag)

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

Tips on how to send Mongoose response variable in NodeJS Express router res.render?

I just finished setting up a basic Express NodeJS server. My goal is to save the value of the setting returned from mongoose.find() as a variable in res.render, but every time I try, it throws an error saying Cannot read property of undefined. Here' ...

Angular 1 and Javascript offer a different approach than using lodash omit and the delete operator

I am facing an issue with a child component where I need to remove properties from an object. Normally, using Lodash, it should work with the following code snippet: this.current.obj = omit(this.current.obj, ['sellerSupportWeb', 'sellerSup ...

Oops! SAPUI5 is encountering an issue with reading property '0' of undefined

Is there a possibility of encountering multiple errors leading to this specific error message? https://i.stack.imgur.com/RpWhw.png Despite searching online, it appears that the error occurs in the JavaScript file when getelementbyid returns null. However ...

Tips for customizing column width in v-simple-table with Vuetify.js component

For my most recent projects UI component, I decided to use vuetify.js. I attempted to adjust the width of the th and td elements within a v-simple-table using CSS, but unfortunately, nothing seemed to happen. My goal was to set the width of every th and td ...

Typography Addition on Flexslider

I am currently working with flexslider and trying to incorporate a unique text overlay on each individual slide, but so far I have been unsuccessful. <div class="flexslider"> <ul class="slides"> <li> <img src ...

Storing a date in MySQL using Vue.js and Node.js

My current tech stack consists of nodejs and express.js for the backend, vuejs for the frontend, and mysql as the database. I am facing an issue where I cannot send a date retrieved from localStorage to my mysql database. Whenever I try to send the date, ...

Encountering an issue in Laravel when trying to retrieve data using relationships and the paginate() method

When I try to fetch data using paginate(10), Vue.js does not work. However, if I use paginate(5), it works fine. The code in the Controller with relationships in the model files is working fine and returns a 200 OK response. $results = Posts::with([' ...

Resolve CORS error when uploading images with AJAX and Node.js using FormData

I am incorporating vanilla javascript (AJAX) to submit a form and utilizing Formdata(). The submission of the form is intercepted by nodejs and linked to a database. However, there is an issue that arises when I try to connect with nodejs after adding a f ...

Changing the Flash message to an Alert message in Symfony2: A step-by-step guide

I've encountered a problem where the success message from an action method in Symfony2 Controller appears as a flash message, but I need to display it as an alert or dialogue message according to requirements. I have attempted various solutions witho ...

Do we need to use aria-labelledby if we already have label and input associated with "for" and "id"?

Here is the HTML structure for the Text Field component from Adobe Spectrum: The <label> element has a for attribute and the <input> has an id which allows screen readers to read out the label when the input is focused. So, why is aria-label ...

Utilizing tag keys for inserting text and adjusting text sizes within a Web application

Creating an online editing interface for coursework where keyboard events are used. The goal is to have the tab key insert text, while also reducing the size of the text on that line. However, upon using getElementById, an error message pops up stating: ...

Ways to apply the .not selector efficiently in jQuery

I have a situation with two separate divs, one named task1 and the other named task2. Each of these tasks contains panels with various names. Within task2, there is a duplicate name (Greg), who also belongs to the duplicate class. I'm trying to figure ...

Restrict a class to contain only functions that have a defined signature

Within my application, I have various classes dedicated to generating XML strings. Each of these classes contains specific methods that take input arguments and produce a string output. In order to enforce this structure and prevent the addition of methods ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

A guide on obtaining the date format according to locale using Intl.DateTimeFormat within JavaScript

Can someone assist me in obtaining the standard date format (such as MM/DD/YYYY) based on a specified local id? The code snippet provided below is not returning the desired format. Any guidance on how to achieve this would be greatly appreciated. var da ...

Automating the selection of a drop down based on a condition in Angular 2: A step-by-step guide

I'm facing an issue with a drop-down menu where no default value is selected. On my homepage, I need to automatically select an option based on query parameters. I've attempted various methods but none have been successful. Below is the code snip ...

Tips for selectively executing a script based on whether the DIV is within the viewport

I have a created a script as shown below: jQuery(function($) { $('.count').countTo({ from: 0, to: '400', speed: '3000', refreshInterval: 50, onComplete: func ...

Is there a way to rearrange the entries in a Vuetify data table by simply dragging the rows?

Currently, I am developing a Vuetify web application for a client who has requested the ability to rearrange the order of elements in a data table by dragging and dropping rows. However, after consulting the documentation provided by Vuetify, I was unabl ...

Completing the pledge using ionic/ui-routing

I've encountered an issue with my promise not resolving as expected while using Ionic/ui-routing. This is the structure of my service: return { all: function () { $localForage.getItem('foo').then(function (bar) { re ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...