How can Conditional Rendering be applied within List Rendering (v-for) in Vue JS?

In my current project, I am utilizing List Rendering (v-for) to display information about various books stored in an array.

One challenge I'm facing is implementing conditional rendering within this loop to dynamically generate li elements that represent each book's category tag.

I want to avoid displaying empty li elements in the DOM. For instance, if we take the first book "Moby Dick", the list of book tags should only include the relevant ones.

How can I achieve this functionality? Here's what I have so far:

<ul>
    <li v-for="book in books">

        <div class="item">
            <div class="item-bd">
                <h2>{{ book.title }}</h2>
                <ul class="book-tags>
                    <li v-if="book.tagOne">{{book.tagOne}}</li>
                    <li v-if="book.tagTwo">{{book.tagTwo}}</li>
                    <li v-if="book.tagThree">{{book.tagThree}}</li>
                </ul>
            </div>
        </div>

    </li>
</ul>


new Vue({
  el: '#app',
  data: {
    books: [
        {
            title: "Moby Dick",
            tagOne: "Kids Book",
            tagTwo: "Fiction",
            tagThree: ""
        },
        {
            title: "Hamlet",
            tagOne: "All Ages",
            tagTwo: "Shakespeare",
            tagThree: "Classic"
        }
    ]
  }
});

Answer №1

When considering your inquiry, a simple way to display three <li> items is by checking if the corresponding tags exist or not like so:

<ul class="book-tags>
  <li v-if="book.tagOne">{{book.tagOne}}</li>
  <li v-if="book.tagTwo">{{book.tagTwo}}</li>
  <li v-if="book.tagThree">{{book.tagThree}}</li>
</ul>

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

Issue with properly assigning data to list items in Vus.js and socket.io due to missing

Hey everyone, I'm facing a strange issue with the code snippet below: created() { socket.on('rooms:App\\Events\\UserJoined', data =>{ this.usersCounter = data.users; }); socket.on('rooms:App&b ...

The error encountered is due to an invalid assignment on the left-hand side

I'm encountering the error below: Uncaught ReferenceError: Invalid left-hand side in assignment This is the problematic code: if (!oPrismaticMaterial = "") { for (var i = 0; i < oPrismaticMaterial.length; i++) { if (oPrismaticMater ...

What is the best way to conceal the header on a 404 error page?

<HeaderContainer> <Switch> <Route exact path='/counters' component={ParentCounterContainer}/> <Route exact path='/about' component={AboutContainer} /> <Route exact path='/' component={H ...

Steps for implementing a Toggle Navigation Bar in CSS

I'm looking to implement a show/hide navigation menu similar to the one showcased in this inspiration source: Code Snippet (HTML) <div id="menus"> <nav id="nav"> <ul> <li><a href="#">HOME</a></li> <li& ...

Vue Select - Enhancing search capabilities by including meta-data in the search process

Looking to integrate the vue-select plugin into my vue app, here is the code I have: <v-select :options="options" label="country" :reduce="country => country.meta.code" v-on:input="set"/> The options avai ...

Is there a way to transform this JSON string into a particular format?

When moving a string from view to controller, I have encountered an issue. Below is the ajax code I am using: var formData = $('#spec-wip-form, #platingspec-form').serializeArray(); var platingId = @Model.PlatingId; var form = JSON.s ...

React does not accept objects as valid children. If you want to render a group of children, make sure to use an array instead

I am in the process of developing a system for document verification using ReactJS and solidity smart contract. My goal is to showcase the outcome of the get().call() method from my smart contract on the frontend, either through a popup or simply as text d ...

The Bootstrap 4 Carousel experiences flickering issues during transitions when viewed on Safari browser

After integrating a Bootstrap 4 carousel onto a Drupal platform, I encountered a peculiar issue. The carousel functions smoothly on Chrome, but on Safari, it briefly blinks before transitioning to the next slide (as per the set interval time). Initially, I ...

What is the method to display my input value within my application interface rather than triggering an alert popup?

Hi there, I am seeking assistance with my GUI code. I want the input value to be displayed as text on the screen, or even better, to look like a chatroom so that I can integrate a simple chatbot later on. My main goal is to have the texts show up in the bl ...

Update elements dynamically using JSX

I have an array called data.info that gets updated over time, and my goal is to replace placeholder rendered elements with another set of elements. The default state of app.js is as follows: return ( <Fragment> {data.info.map((index) =&g ...

How is the rendering of a confirm/alert decided?

While browsing, I stumbled upon this intriguing query related to alerts and confirm dialogs, such as the one generated by alert('Hello World!'). My quest was to find a method to modify the text on the 'ok' and 'cancel' buttons ...

Error: 'require' is undefined in react.production.min.js during production deployment

Greetings! I am encountering some difficulties while trying to build on production: the error "require is not defined" is being caused by react.production.min.js. Below are my webpack.config.js and package.json files: webpack.config.js const path = requi ...

Integrate third-party code into your Angular application

I've been working on an Angular project and I wanted to spice things up by adding a confetti animation. I found this cool animation that I'd like to incorporate into my project: http://jsfiddle.net/vxP5q/61/?utm_source=website&utm_medium=emb ...

Experimenting with parallelism using TypeScript/JS

Currently, I am tackling a TS project that involves testing concurrent code and its interactions with a database, specifically focusing on idepotency. My goal is to ensure that multiple requests modifying the same resource will either apply changes correct ...

I'm having trouble retrieving data from the server using the AngularJS $http.get() function. What am I doing wrong

Ensure that your question is clear and that your code properly showcases the issue at hand. Feel free to leave any questions or comments below for clarification. app.js var express = require('express'); var app = express(); app.use(express.sta ...

Executing a series of post requests within a loop and handling nested promises

Hello, I'm looking for some assistance! I'm attempting to send a post request for each item in an array. The issue I'm facing is that I need to aggregate the responses from each post request and then pass the count array back to the callin ...

jQuery fails to fetch information

I am currently working with a straightforward script as shown below: $(function() { var url = theme_directory + '/func/api.php'; $.get( url, function(data) { alert("Data Loaded: " + data); }); }); Here is the code for api ...

"Adding a grid panel to the final node of a tree-grid in extjs: A step-by-step guide

Does anyone have a suggestion on how to add a grid panel to the last node/children of a treepanel dynamically? I would like to append the gridpanel dynamically and for reference, I am providing a link: Jsfiddle I also need to ensure that the gridpanel is ...

Leveraging v-model within scoped slots

Currently, I am utilizing Vue 2.6.9 with the latest v-slot syntax. My goal is to be able to access and interact with v-model inside a slot. The issue I am encountering is that although displaying data inside the slot is functional, using v-model is not. Be ...

"Using the Google Maps directive inside a separate modal directive in Angular results in a blank map display

As a newcomer to Angular, I have encountered a hurdle while attempting to incorporate a 'google maps' directive inside another directive. The following code showcases a 'modal-view' directive that loads a form: angular.module(&apo ...