0

I am using List Rendering (v-for) in my project to print each item in my array to show information on a series of books.

However, I am trying to use conditional rendering within this loop, in order to print a number of li elements that contain the book's category tag.

I do not want the li to be painted in the DOM if there is no data stored in my array. For example, for the first book, Moby Dick, the ul for the book tags would just contain two HTML list items.

How can this be done? I have the following 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}}</li>
                    <li v-if="">{{book.tagTwo}}</li>
                    <li v-if="">{{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"
        }
    ]
  }
});
2
  • 3
    Put the tags in an array instead and use the exact same mechanism (v-for). If you want to stick to three fixed tags, just use v-if="book.tagOne". The fact that this is happening inside a v-for list doesn't matter one bit, afaik. Commented Apr 28, 2020 at 10:58
  • @ChrisG Thank you Chris. I guess I was missing the book.tagOne etc inside conditional tag. I will also look at how to use an array as it must be a more DRY method. Commented Apr 28, 2020 at 11:03

1 Answer 1

1

Based on your question, if you want to keep three <li> items then simply you can check if respective tags exist or not as below:

<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>
Sign up to request clarification or add additional context in comments.

1 Comment

the problem I have is that if i change one property ( lets say book.tagOne) , the component does not re render .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.