Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oddity with templates and root node with vue.js

Tags:

vue.js

I think this is possibly a bug I've stumbled across, not sure. I'm getting this Vue.js warning for a component:

vue.js:2611 [Vue warn]: Cannot use <template> as component root element because it may contain multiple nodes:

The problem seems to be this:

<template id="tpl-field">
    <template v-if="fieldType==='checkbox-inline'">
        <label class="checkbox-inline">[SNIP]</label>
    </template>
    <template v-else>
    [SNIP]
    </template>
</template>

So I have two template nodes, which seems to be the multiple nodes it's choking on (certainly each of the template nodes contains just a single node). Yet this is an if-else in Vue - if one of the nodes is present, the other logically cannot be.

Demo of the problem here: https://jsfiddle.net/jonmor51/Ldz3k0jp/1/. If I wrap everything in a div, it works. But without, it fails. (Unfortunately, in the context where I want to use this, namely for inline checkboxes within a Bootstrap grid, wrapping in a div breaks things).

like image 409
John Moore Avatar asked Dec 02 '16 19:12

John Moore


2 Answers

Not sure if this will solve your problem with bootstrap... but you could wrap you inner templates with a <transition> tag and set a key to each one.

Please check this working fiddle

https://jsfiddle.net/AldoRomo88/7c7znu3p/

like image 195
AldoRomo88 Avatar answered Nov 05 '22 22:11

AldoRomo88


helpful thing - just use div display: contents as a root of the component and browser will ignore that element and consider child elements (which can be many) as children of upper dom element

    <div style="display: contents">
        <template v-if="...">
            <template v-for="..."> ...
        </template>
        <template v-if="...">
        </template>
    </div  

works even inside tables!

like image 40
Andrey Avatar answered Nov 05 '22 21:11

Andrey