Skip to content
Advertisement

Vue & conditional rendering with template tag

I am trying to follow documentation:

But for some reason my template is not working as expected, as soon as I put <template v-if="variable"> vue fails to render anything.

<script type="text/x-template" id="dashboard-inititial-message">

<template v-if="okBoom">
    <h1>Title</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</template>

<div v-if="ok">
    <h1>Title</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</div>
<div v-else>
    <p>ELSE</p>
</div>
</script>

Any advice?

Snippets that demonstrate problem:

https://jsfiddle.net/o2tL2ems/1/

Advertisement

Answer

There is a thing to know about vue.js, Peter pointed it out in a comment. Template cannot be a root element and in general root tag can be only one.

So when you have template like this:

<script type="text/x-template" id="dashboard-inititial-message-mk1">
    <div v-if="okBoom">
        <h1>Title</h1>
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
    </div>
    <h3>adas</h3>
    <div v-if="ok">
        <h1>Title</h1>
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
    </div>
</script>

You basically asking vue.js for problems. Vue will stop parsing your template as soon as div with okBoom ends.

There are questions similar to mine all over the internet:

Solution in short. Wrap your template into master span, div or transition (this one however seems to be a bit hacky, on the other hand it won’t generate unnecessary html tags).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement