无法在组件内部渲染组件

时间:2019-05-04 16:32:54

标签: javascript vue.js

我有非常基本的Vue应用程序(在Rails上):

hello_vue.js:

import Vue from 'vue/dist/vue.esm'
import TurbolinksAdapter from 'vue-turbolinks'
Vue.use(TurbolinksAdapter)

import CollectionSet from '../collection_set.vue'

document.addEventListener('turbolinks:load', () => {
  const app = new Vue({
    el: '#app',
    components: { CollectionSet }
  })
})

collection_set.vue:

<script>
import Collectable from './collectable.vue'
export default {
  components: { Collectable }
}
</script>

<template>
  <p>test</p>
  <collectable />
</template>

collectable.vue:

<script>
export default {
  name: 'collectable'
}
</script>
<template>
  <p>test 2</p>
</template>

我的网页:

<div id="app"><collection-set /></div>

在上面的示例中,我什么都没有看到,但是当我从<collectable />中删除collection_set.vue时,我看到了test。我没有任何错误。

为什么不呈现collectable

2 个答案:

答案 0 :(得分:3)

将collection_set.vue的template代码更改为

<template>
 <div>
    <p>test</p>
  <collectable />
</div>
</template>

错误的原因是Component template should contain exactly one root element 在这里,我们试图创建两个根元素pcollectable

现在,我将其包装在父div容器中,它可以正常工作。 请尝试并让我知道是否有帮助。

一个建议是,始终检查浏览器devtools的控制台以检查可能是什么问题。在这种情况下,控制台给出了确切的错误,并且代码编译也因相同的错误而失败。

答案 1 :(得分:0)

在Vue中,每个组件都必须只有一个根元素,这意味着您需要在模板中包含<p><div>之类的标签。

相关问题