Oddity with templates and root node with vue.js

2019-06-23 04:04发布

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).

标签: vue.js
2条回答
何必那么认真
2楼-- · 2019-06-23 04:49

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/

查看更多
倾城 Initia
3楼-- · 2019-06-23 05:07

The inner templates direct children, are they single elements? If so, you can just remove the inner templates and move v-if to the label.

Or, just use span rather than div as your quick fix, which won't break inline elements' style.

查看更多
登录 后发表回答