gpt4 book ai didi

vue.js - 为什么将这个简单的 VueJS 2.x 组件从嵌套的 HTML 表格元素中吊出?

转载 作者:行者123 更新时间:2023-12-03 06:47:15 33 4
gpt4 key购买 nike

我使用的是 VueJS 2.6.12 的开发版本。

在我的 HTML 中,我有一个看起来像这样的 VueJS 模板(为了小示例,我将其删除):

<div>
<table class="table">
<thead>
<tr><th>AAA</th><th>BBB</th></tr>
</thead>

<tbody id="main">
<my-item v-for="item in dataset" :d="item" :key="item.key"/> <!-- (this part works) -->
</tbody>
</table>
</div>

在我的 JavaScript 中,我定义了一个全局 Vue 组件(这有效,显示了我的数据):

Vue.component('my-item', {
props: ["d"],
template: `<tr><td>{{this.d.AAA}}</td><td>{{this.d.BBB}}</td></tr>`
});

当我加载页面时,我看到我的数据正确呈现,但表格标题位于底部。 tr 元素(包含我的数据)存在,尽管 table 之外。

在浏览器检查器中查看 DOM 显示 VueJS 构建了这个结构,将元素提升到 tbody 甚至 table 本身之外:

<div>
<tr><td>aaa</td><td>bbb</td></tr> <!-- Why are these two rows outside the table? -->
<tr><td>yyy</td><td>zzz</td></tr>
<table class="table">
<thead>
<tr><th>AAA</th><th>BBB</th></tr>
</thead>
<tbody id="main"></tbody>
</table>
</div>

为什么会发生这种情况,我该如何解决?我希望将我的 ... 元素注入(inject)到 tbody 中在 thead 标题行下。


更奇怪的是,如果我在上面和下面手动添加一些行:

    <tbody id="main">
<tr><td>111</td><td>222</td></tr>
<my-item v-for="item in dataset" :d="item" :key="item.key"/>
<tr><td>888</td><td>999</td></tr>
</tbody>

那些确实得到保存:

<div>
<tr><td>aaa</td><td>bbb</td></tr> <!-- ...but these still got hoisted out if the table -->
<tr><td>yyy</td><td>zzz</td></tr>
<table class="table">
<thead>
<tr><th>AAA</th><th>BBB</th></tr>
</thead>
<tbody id="main">
<tr><td>111</td><td>222</td></tr>
<tr><td>888</td><td>999</td></tr>
</tbody>
</table>
</div>

最佳答案

呃,被 same problem 咬了,形式略有不同。

简而言之,有DOM Parsing Caveats ,以及类似 table 的元素对哪些元素可以出现在其中有限制。 (仅供引用:ulolselect 也有此问题)。

解决方案是使用 VueJS 的 is attribute :

<div>
<table class="table">
<thead>
<tr><th>AAA</th><th>BBB</th></tr>
</thead>

<tbody id="main">
<!-- Specify the element, but then use is="component-name" -->
<tr is="my-item" v-for="item in dataset" :d="item" :key="item.key"/>
</tbody>
</table>
</div>

这将使模板解析顺利,如table (和 tbody )将获得“tr ”元素,但其内容将由命名组件呈现。


重要:从 VueJS 2(如上所示)到 VueJS 3 的重大更改。

在 VueJS 2 中 is="..."在 VueJS 3 中变成了 `v-is="..."。

另外,VueJS 2 采用了一个字符串,而 VueJS 现在采用了一个 Javascript 表达式,这意味着您必须向它传递一个字符串,例如<tr v-is="'my-item'">带引号。

参见 https://v3.vuejs.org/guide/component-basics.html#dom-template-parsing-caveatshttps://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html#v-is-for-in-dom-template-parsing-workarounds了解详情。

关于vue.js - 为什么将这个简单的 VueJS 2.x 组件从嵌套的 HTML 表格元素中吊出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64165050/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com