从自定义表格广告位中删除了THEAD,TBODY,TR HTML元素

时间:2018-06-30 01:21:26

标签: vue.js vuejs2

我正在尝试学习VueJS。我仍然是初学者,所以请您谅解。

我有一个.vue文件,该文件呈现了一个自定义表格元素。

<template>
    <table v-bind:class="classes">
        <slot></slot>
    </table>
</template>

<script>
    export default {
        data() {
            return {
                styles: {
                    separator: 'separator',
                    solid: 'bg',
                    bg: 'bg'
                }
            };
        },
        props: {
            type: { default: 'separator' },
            theme: { default: 'primary' }
        },
        computed: {
            classes: function () {
                return `table m-table m-table--head-${this.styles[this.type]}-${this.theme}`;
            }
        }
    }
</script>

在我试图创建模板的HTML文件中,它看起来像这样:

<custom-table type="solid" theme="primary">
    <thead>
        <tr>
            <th>Column 1</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Value 1</td>
        </tr>
    </tbody>
</custom-table>

但是,当页面呈现时,<slot>中的所有html都会被删除,仅保留文本:

enter image description here

如果我打电话给$vm0.$slots.defaults[0].elm,我得到的只是text,没有HTML,没有<thead>等。

我在网上搜索了vuejs2 stripping out html from slots,但找不到与为什么有关的任何信息。

我知道我的.vue文件目前可能并不完美,我只是在尝试了解基础知识。

感谢任何帮助,为我指出了为什么要剥离HTML(或其他可能的原因)的正确方向。

1 个答案:

答案 0 :(得分:1)

这是由于HTML中的限制所致:即使对于自定义元素,表子项(例如<thead><tr>等)也只能出现在<table>中。

使用自定义表的官方解决方法是使用HTML属性is,该属性受Vue支持:

<table is="custom-table" type="solid" theme="primary">
    <thead>
        <tr>
            <th>Column 1</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Value 1</td>
        </tr>
    </tbody>
</table>

请参见vue.js: what's the difference between <component :is="comp-name"/> and <div :is="comp-name"/>?