问题
I am trying to follow documentation:
- https://vuejs.org/v2/guide/conditional.html
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/
回答1:
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:
- Oddity with templates and root node with vue.js
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).
回答2:
I use conditional template rendering for loaders (while a server request is taking place)
new Vue({
el: "#app",
template:
`<div v-else class='somePage'>
<template v-if="isLoading">
<div>LOADING...</div>
</template>
<template v-else>
<h1>title</h1>
<p>The final rendered result will not include the "template" element.</p>
</template>
</div>`,
data: () => ({
isLoading: true
}),
mounted() {
setTimeout(this.getData.bind(this), 1500);
},
methods: {
async getData() {
// await axios ...do some request...
this.isLoading = false
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
来源:https://stackoverflow.com/questions/42373918/vue-conditional-rendering-with-template-tag