我正在使用 Vue 的单文件组件规范 (*.vue
( 在我的应用程序中自定义组件。与rollup
和rollup-plugin-vue
一起,我观察到 DOM 中的输出,对于我编写的自定义组件,由等效的 html 元素组成。
例如:
component-a.vue
<template>
<span>Hello World</span>
</template>
<script>
export default { name: 'component-a' };
</script>
component-b.vue
<template>
<component-a></component-a>
</template>
<script>
import ComponentA from './path/to/component-a.vue';
export default { name: 'component-b', components: { ComponentA } };
</script>
上面的例子,如果component-a
被添加到 Vue 挂载组件中,将在 DOM 中呈现两个组件的模板内容的总和,在这种情况下,它只是一个span
元素:
<span>Hello World<span>
是否可以像下面的代码片段一样在 DOM 中实现呈现的输出,以便自定义元素的模板在 DOM 中由保留其标签名称的标签表示?
<component-b>
<component-a>
<span>Hello World</span>
</component-a>
</component-b>
在你的component-a.vue
中,你应该能够通过在你的<template>
标签中包含一些html代码来实现这一点,如下所示
component-a.vue:
<template>
<customelement>
// Other stuff
</customelement>
</template>
通过这种方式,您将能够从应用程序中的任何位置调用组件 a,并呈现名为customelement
的元素。
理想情况下,你应该使用这个"技巧"来渲染标准的HTML5元素,否则你可能会在vue应用程序控制台中看到一些错误。让我知道它是怎么回事。
参考 Vuejs 文档 https://v2.vuejs.org/v2/guide/components.html#DOM-Template-Parsing-Caveats
应该注意的是,如果您 使用以下源之一的字符串模板:
String templates (e.g. template: '...') Single-file (.vue) components <script type="text/x-template">
如果你像上面的例子一样使用 Vuejs,你不会得到你想要的结果。因此,如果您以其他方式渲染组件,您应该获得所需的结果。