VueJs v-for渲染div但不渲染表格行吗?

时间:2019-10-29 15:22:49

标签: html css vue.js rendering

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

<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而不是表行,但是我很想这样做。有什么想法为什么会这样?

2 个答案:

答案 0 :(得分:1)

您不能直接在tr标签内使用“行”属性,需要td标签

  

像这样

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

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

答案 1 :(得分: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

解决方案就是在模板中包含<td>

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