【问题标题】:VueJs v-for renders divs but not table rows?VueJs v-for 渲染 div 但不渲染表格行?
【发布时间】:2019-10-29 15:22:49
【问题描述】:

我无法理解为什么会这样!所以,这段代码:

<div class="container">
    <div class="row" v-for="rows in data.Rows"> {{ rows }} </div>
</div>

将渲染对象中的所有行。 但是,当我在表中使用相同的语法时:

<table>
   <tr v-for="rows in data.Rows"> {{ rows }} </tr>
</table>

我得到错误:

[Vue warn]: Property or method "rows" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. 

为什么在表格中使用这样的 v-for 会出现问题?我想要一个表格来显示数据,因为它更适合这种情况下的目的。否则我会选择 div 而不是表格行,但我希望它能够正常工作。关于为什么会发生这种情况的任何想法?

【问题讨论】:

  • 这个模板在哪里?它是直接在 HTML 文件中吗?
  • 能否用 row.Rows 中的示例对象更新问题?

标签: html css vue.js rendering


【解决方案1】:

如果您直接在 HTML 文件中使用该模板(而不是模板字符串或 SFC),则浏览器会在它到达 Vue 之前对其进行解析。浏览器对表格以及其他元素中允许哪些元素很挑剔。

下面的示例显示了浏览器如何将您的模板解析为 DOM 节点。注意{{ rows }} 是如何移动的:

let html = document.getElementById('app').innerHTML

html = html.replace(/</g, '&lt;').replace(/>/g, '&gt;')

document.getElementById('output').innerHTML = html
#app {
  display: none;
}
<div id="app">
  <table>
    <tr v-for="rows in data.Rows"> {{ rows }} </tr>
  </table>
</div>
<pre id="output">
</pre>

Vue 试图运行的正是模板的这个错位版本,如您所见,{{ rows }} 已移出v-for,导致错误。

官方文档在这里介绍了这一点:

https://vuejs.org/v2/guide/components.html#DOM-Template-Parsing-Caveats

解决方案就是在您的模板中包含&lt;td&gt;

<table>
   <tr v-for="rows in data.Rows">
     <td>{{ rows }}</td>
   </tr>
</table>

【讨论】:

  • 有道理...我今天学到了一些新东西!在 vuejs.org 上没有找到文档,但我会更多地阅读它。现在就像一个魅力。非常感谢!
【解决方案2】:

tr标签内不能直接使用rows属性,需要td标签

喜欢这个

<table>
    <tr class="row" v-for="rows in data.Rows"> <td>{{ rows }} </td></tr>
  </table>

在这里工作的codepen:https://codepen.io/chansv/pen/dyyVybK

【讨论】: