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

Why does the del command delete the parent folder as well?

I am looking to remove all files within the ./dist/* directory while leaving the ./dist folder itself untouched (it should be empty once the task completes). const del = require('del'); gulp.task('clean:dist', function(cb){ del([ ...

Combining load and change events in jQuery at the same time

Often times, I find myself needing to attach a behavior to an element both after it has loaded and after a specific event has been triggered (such as "change"). I believe the most efficient approach would be to combine these actions in one line: $('# ...

What is the best way to verify a password's strength with Joi so that it includes 2 numbers, 2 special characters, 2 uppercase letters, and 2 lowercase letters?

Is there a way to achieve this using Joi? For instance: Joi.string() .required() .min(8) .max(16) .pattern(/(?=(?:.*[a-z]){2,16}).+/) .pattern(/(?=(?:.*[A-Z]){2,16}).+/) .pattern(/(?=(?:.*[0-9]){2,16}).+/) .pa ...

Ways to store debug logs in a file within my project

In the project I am currently working on, I incorporate the Debug package which can be found at https://www.npmjs.com/package/debug. As part of this setup, I have set an environment variable (variable name: DEBUG & value:*). As a result, I am able to vie ...

Formatting dates in JavaScript

When using the jQuery datepicker, my goal is to set a minimum and maximum date range for users to select from. I also need to ensure that the date format is based on the user's locale. In this case, there are two date fields: Start date and End date. ...

How come this straightforward VueJS component template is appearing in the wrong location in the DOM, positioned above a table?

These illustrative examples are not the actual faulty code, but rather simplified for discussion purposes. Issue with Code The code snippet below displays a table, but unexpectedly places the Component values above the table element visually and in the D ...

Calendar complete: ActiveRecord::RecordNotFound (Event with 'id' = update not found)

I'm currently facing an issue with integrating FullCalendar into my rails application. Specifically, I am encountering difficulties with saving after performing drag-and-drop actions. Within my application, I have two models - Event and Workout. The ...

Embed the aspx file within the background-image attribute similar to how an image source is

Within my asp.net application, there is an image tag linking to another aspx file in the src attribute, displaying a picture. <img src="/picture.aspx?Param=3" alt="picture"/> I need to convert the image tag into a div with a background-image proper ...

Having trouble figuring out how to update a list using ajax in Yii

I need to modify a JavaScript function that filters the content of a list. The current code looks like this: var id = $(this).data('id'); $.fn.yiiListView.update('contests-list', { data: {category: 2} }); I couldn't find any ...

Storing cookies is not supported when using jQuery for authentication with Passport.JS

My software setup includes an Electron app for the frontend and a Node backend. After clicking the login button, the app sends an Ajax POST request to the backend, which confirms successful authentication. However, when checking if the user is authentica ...

Issues with Line Chart in D3: Scaling and Zoom not functioning as expected due to ClipPath limitations

I am utilizing D3 version 4 to process data and create a graph based on dates. Although I have successfully adjusted everything to be compatible with zoom functionality, I am struggling to prevent the line from extending beyond the chart axes. I would pre ...

Passing data from an Express middleware to a Jade template

My KeystoneJS app is all set up, using Express and Jade. The default.jade file sets up a fullscreen background image along with various imports, the header, and footer of the site. I am attempting to rotate the image based on a selection of images stored ...

Should WordPress files be kept separate (php, css, and js) or combined into a single file?

Currently, I am updating my WordPress website with a goal of minimizing the number of plugins used. To achieve this, I prefer writing code only for essential functionalities. In order to optimize my work with php, css, and javascript files, I have been exp ...

Angular.js encountered an error at line 13550: [ng:areq] The argument 'popCntrl' is expected to be a function, but it was undefined

I have been diving into learning AngularJS on my own recently, and I've been attempting to create a basic popup feature. However, I keep encountering the error mentioned in the title. While searching for solutions, I haven't found any examples th ...

Shadows persist despite light intensity being reduced to 0 during runtime

Struggling to figure out how to get rid of these persistent shadows... During runtime, I attempt: light.intensity = 0.0; This makes the scene darker (which is good), but the shadows created by the light remain visible. I've experimented with both ...

Using jQuery to trigger an event when an element is empty or when the element contains children nodes

Is there a way to create a jQuery script that can monitor the children of an element? If the element does not have any children, default scrolling for the entire page is enabled. If the element has children, scrolling for the whole page is disabled. The ...

Filtering for Material Autocomplete is limited to the getOptionLabel field

Currently, I am utilizing the Google Material-UI autocomplete component. It is currently only filtering based on the "getOptionLabel" option field when text is entered into the input field. However, I would like the autocomplete to filter based on more tha ...

The "click" event is only effective for a single use

I am looking for a way to trigger the click event more than once in my project. I attempted using "live" but it didn't work as expected. There are 2 other similar scripts in this Django project. If you have any suggestions on improving this project, p ...

How to add vertical bars within ng-repeat in AngularJS

I attempted to retrieve values from an array variable using ng-repeat within unordered lists. Although the values are displaying correctly and everything is functioning properly, I added vertical bars after each value to represent sub-categories on my page ...

The following middleware is not functioning properly on a local SSL server

When I run my Nextjs app without SSL using "next dev", the middleware functions as expected without any errors. However, if I attempt to run the app with SSL enabled, an empty middleware function triggers an error. The code for the middleware function (l ...