首页 > 解决方案 > 一个组件的多个实例被解析为一个

问题描述

考虑一下:

<div id="app">
  <test-component to="abc">Some ABC</test-component>
  <test-component to="xyz">Some XYZ</test-component>
  <test-component to="123">Some 123</test-component>
</div>

----

Vue.component('test-component', {
  template: '<a :href="to"> <slot></slot> </a>',
  props: ['to'],
});

new Vue({
  el: "#app",
})

所有三个“测试组件”都按预期呈现。见https://jsfiddle.net/gotp1fdL/1/

但是,当我实现一个包装 App 组件时,只有第一个“测试组件”被渲染,其他的甚至被忽略......见https://jsfiddle.net/gsxq9ajc/

<div id="app">
  <app></app>
</div>

<template id="application">
  <test-component to="abc">Some ABC</test-component>
  <test-component to="xyz">Some XYZ</test-component>
  <test-component to="123">Some 123</test-component>
</template>

---

Vue.component('test-component', {
    template: '<a :href="to"> <slot></slot> </a>',
    props: ['to'],
});

Vue.component('app', {
    template: '#application',
});

new Vue({
  el: "#app",
})

请问有人可以解释为什么吗?让所有组件独立呈现而没有问题,缺少什么?

标签: vue.js

解决方案


问题如下,如控制台所示:

vue.js:634 [Vue 警告]:编译模板时出错:

组件模板应该只包含一个根元素。如果您在多个元素上使用 v-if,请改用 v-else-if 链接它们。

在您的应用程序组件中添加包装器将修复它。

<template id="application">
  <div>
    <test-component to="abc">Some ABC</test-component>
    <test-component to="xyz">Some XYZ</test-component>
    <test-component to="123">Some 123</test-component>
  </div>
</template>

推荐阅读