Reputation: 71
So I currently have a template sitting in a ".vue" file like so:
<template>
<div id="dataAttachToMe"></div>
</template>
I don't want this to load, unless a user clicks a button, something like
<button @click="loadTheTemplateAbove">See Data</button>
I've tried using this example:https://v2.vuejs.org/v2/guide/conditional.html#Controlling-Reusable-Elements-with-key. But it says something like "Component template should contain exactly one root element" in the error message.
I need more than a show/hide here I think, something that can initiate the template dynamically.
<template>
<div id="data">
<button @click="loadTemplate">Load the template</button>
<div v-if="buttonClicked">
<div id="dataAttachedToThisDiv"></div>
</div>
</div>
</template>
Upvotes: 3
Views: 4821
Reputation: 2131
Welcome to StackOverflow. When you get the error Component template should contain exactly one root element
it means that you can only have one root element in your template
. You can fix that error by wrapping everything in a blank div
like so
<template>
<div>
<template v-if="loginType === 'username'">
<label>Username</label>
<input placeholder="Enter your username">
</template>
<template v-else>
<label>Email</label>
<input placeholder="Enter your email address">
</template>
</div>
</template>
Please edit your post and place you <script>
tag. Conditional Rendering requires a data field of a boolean that you can place in your if
statement on your template
<template>
<div>
<div v-if="show">{{message}}</div>
<div v-if="@show">Not Showing when show is set to false</div>
<button v-on:click="show = true">Show</button>
</div>
</template>
<script>
module.exports {
data: function () {
message: 'Hello Vue!',
show: false
}
}
</script>
Upvotes: 0
Reputation: 4732
The error you are getting, means that there is more than one root element inside <template></template>
tag.
It is required in Vue.js (and other template based frameworks/libraries) to have only one root element.
This will NOT work:
<template>
<div id="dataAttachToMe"></div>
<button @click="loadTheTemplateAbove">See Data</button>
</template>
This will work:
<template>
<div id="someRootDiv">
<div id="dataAttachToMe">Some data</div>
<button @click="loadTheTemplateAbove">See Data</button>
</div>
</template>
Here is a code example (App.vue
) of what you are trying to achieve:
Basic idea: we have to create a variable, that will be changed upon button click. We add v-if
directive that depends on that variable and will handle element's visibility.
Upvotes: 2