【问题标题】:Removing a row from a table with VueJS使用 VueJS 从表中删除一行
【发布时间】:2017-07-20 21:45:04
【问题描述】:

在Vue中,当项目被删除时如何从表中删除一行?

下面是我如何渲染表格

<tbody>
  <tr v-for="item in items">
    <td v-text="item.name"></td>
    <td v-text="item.phone_number"></td>
    <td v-text="item.email"></td>
    <td><button @click="fireDelete(item.id)">Delete</button></td>
  </tr>
</tbody>

以下是我的 Vue 组件的摘录。

data() {
      return {
        items: []
      }
    },

methods: {
    fireDelete(id) {
        axios.delete('/item/'+id).then();
    }
},
mounted() {
      axios.get('/item').then(response => this.items = response.data);
    }

axios.get 起作用,axios.delete 也起作用,但前端没有反应,因此该项目仅在页面刷新后从表中删除。我如何让它删除相关的&lt;tr&gt;

【问题讨论】:

  • 您想要删除 tr 还是删除 td
  • &lt;tr&gt; 每个代表一个数据库表行。从数据库中删除行后,我还想删除相应的&lt;tr&gt;
  • 如果您的 organisations 项目没有动态链接到您的数据库,则前端将永远不会更新。两种解决方案:想办法将它们链接起来,或者在fireDelete方法中删除organisations数组中的项。
  • 抱歉,修改了代码。组织=项目。在我从数据库中删除记录后,我试图从数组中删除一个项目,但似乎没有任何效果

标签: vuejs2 vue-component


【解决方案1】:

您可以尝试将您的@click="fireDelete(item.id)" 部分修改为自定义方法@click='deleteData(items, item.id)'

然后做一些类似的事情:

methods: {
  deleteData (items, id) {
    this.items = null // These parts may not 
    this.fireDelete(id) // match your exact code, but I hope
  }                     // you got the idea.
}

你的模板可以做到:

<tbody>
  <tr v-for="item in items" v-if='items'>
   <td v-text="item.name"></td>
   <td v-text="item.phone_number"></td>
   <td v-text="item.email"></td>
   <td><button @click="deleteData(item,  item.id)">Delete</button></td>
  </tr>
</tbody>

【讨论】:

  • 如果我将项目设置为null 不会删除每一行吗?
  • 它会的,实际上当我问你是否要删除 row 或 td 时,我也是这么想的。我看不到您如何访问代码中的项目。您的数据中只有组织。如果您添加它,我可以帮助删除特定项目。
  • 是的,我只想删除单击删除按钮的行
  • 多行是否可以访问items?如果没有,那么这个解决方案可以正常工作,否则我需要编辑。
【解决方案2】:

我想出了一个好办法。我将索引传递给 fireDelete 方法并使用 splice 函数。完全按照我的意愿工作。

<tbody>
  <tr v-for="(item, index) in items" v-bind:index="index">
    <td v-text="item.name"></td>
    <td v-text="item.phone_number"></td>
    <td v-text="item.email"></td>
    <td><button @click="fireDelete(item.id, index)">Delete</button></td>
  </tr>
</tbody>


fireDelete(id, index) {
        axios.delete('/item/'+id).then(response => this.organisations.splice(index, 1));
      }

【讨论】:

  • 索引的作用是什么?
  • 要知道数组中的哪个项目要“拼接”,也就是删除。 Splice 以数组索引为参数
  • 不确定组织的来源。
【解决方案3】:

我遇到了和这个问题一样的麻烦。所以也许有人会觉得这很有用。

对于button 使用:

v-if="items.length > 1" v-on:click="fireDelete(index)"

还有fireDelete 函数:

fireDelete: function (index) { 
    this.photos.splice(index, 1);
}

【讨论】:

  • 不确定照片的来源。
猜你喜欢
  • 2021-07-20
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
  • 2016-05-29
  • 2019-12-17
  • 1970-01-01
  • 2021-08-18
  • 2018-12-22
相关资源
最近更新 更多