首页 > 解决方案 > 带有 Vue(2) 绑定的 HTML 表格行

问题描述

我有一个购物车/订单列表,我绑定到一个工作正常的数组。

我最近为添加到数组中的每个项目添加了一个行号,还有一个按钮行。问题是我像这样将它们绑定到当前行

<div id="table">
    <table class="table table-sm table-bordered table-striped">
      <thead class="thead-dark">
        <tr>
          <th scope="col">#</th>
          <th scope="col">Product</th>
          <th scope="col">Type</th>
          <th scope="col">Attribute</th>
          <th scope="col">Height</th>
          <th scope="col">Width</th>
          <th scope="col">Price</th>
          <th width="1%" scope="col">Remove</th>
        </tr>
      </thead>
        <tbody>
          <tr v-for="(item, index) in table_products">
            <td>{{ index +1 }}</td>
            <td>{{ item.product }}</td>
            <td>{{ item.type }}</td>
            <td>{{ item.attribute }}</td>
            <td>{{ item.height }}</td>
            <td>{{ item.width }}</td>
            <td>{{ item.price }}</td>
            <td><button class="btn btn-danger" @click="deleteRow(index)">X</button></td>
          </tr> 
        </tbody>
      </table>
    </div>
  </div>

我从来没有遇到过问题,因为绑定的项目值为空,因此从未创建该行。但是现在索引和按钮创建了表格的第一行。

有没有办法可以在页面加载时清除数组,还是我走错了路?

页面加载表

编辑:为上下文添加了我的 vue 组件

var table_products = new Vue ({
   el : '#table',
   data : {
     table_products : [{
    }]
   },

标签: javascripthtmlvuejs2

解决方案


我初始化 table_products [{}]而不是[]

从初始化开始,它在数组中有一个空对象,因此它有一个元素。初始化一个空数组反而解决了这个问题,因为它没有元素。

感谢评论中的菲尔


推荐阅读