0

I would like to know how to use Vuejs to output a conditional sublist. In this example, not all topics have a subtopic.

new Vue ({
    el: '#maincontainer',
    data: {
        topics: [
            { topicname: 'Introduction' },
            { topicname: 'First Chapter', 
                subtopics: [
                    {subtopicname: 'Test'}
                ]
            },
        ]
    }
});

My HTML so far looks like this:

<li v-for="topic in topics" id="item-{{$index}}">
    {{ topic.topicname }} 
     <ul>
       <li v-for="subtopic in subtopics">
         {{ subtopic.subtopicname }}
       </li>
     </ul>
</li>

How might I have the list optionally add a sublist if there is one in the data?

1 Answer 1

1

v-if is the directive to be used for conditional rendering.

Here you could use v-if='topic.subtopic' too (as long as the value of the expression evaluates to a truthy boolean value if subtopic existed.)

<li v-for="topic in topics" id="item-{{$index}}">
{{ topic.topicname }} 
   <ul v-if='Array.isArray(topic.subtopic)'>
     <li v-for="subtopic in topic.subtopics">
       {{ subtopic.subtopicname }}
     </li>
   </ul>
 </li>

You might also be interested in v-else

Sign up to request clarification or add additional context in comments.

Comments

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.