【问题标题】:How to preserve custom component tag names in Vue.js如何在 Vue.js 中保留自定义组件标签名称
【发布时间】:2018-02-01 15:06:42
【问题描述】:

我正在为我的应用程序中的自定义组件使用 Vue 的单文件组件规范 (*.vue)。与rolluprollup-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中两个组件的模板contents之和,在这种情况下,它只是一个@ 987654330@元素:

<span>Hello World<span>

是否可以像下面的 sn-p 那样在 DOM 中实现渲染输出,这样自定义元素的模板在 DOM 中由保留其标签名称的标签表示?

<component-b>
  <component-a>
    <span>Hello World</span>
  </component-a>
</component-b>

【问题讨论】:

标签: vue.js vuejs2 custom-element rollup


【解决方案1】:

参考 Vuejs 文档 https://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,你将不会得到你想要的结果。所以如果你用其他方式渲染你的组件,你应该得到你想要的结果。

【讨论】:

    【解决方案2】:

    在您的component-a.vue 中,您应该能够通过在您的&lt;template&gt; 标记中包含一些html 代码来实现这一点,如下所示

    component-a.vue:

    <template>
        <customelement>
            // Other stuff
        </customelement>
    </template>
    

    通过这种方式,您将能够从应用中的任何位置调用您的 component-a,并呈现名为 customelement 的元素。

    理想情况下,您应该使用此“技巧”来呈现标准 HTML5 元素,否则您可能会在 vue 应用程序控制台中看到一些错误。告诉我进展如何。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-29
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      • 2019-10-26
      • 1970-01-01
      • 2014-01-07
      相关资源
      最近更新 更多