【问题标题】:Re-render table after deleting item删除项目后重新渲染表格
【发布时间】:2022-07-23 01:09:05
【问题描述】:

我正在尝试创建一个显示来自服务器的数据的表。删除方法有效,但只有在刷新页面后才会显示在表格上。删除项目后如何强制组件重新渲染? this.$forceUpdate 不起作用。

这是删除函数:

async deleteProduct(id) {
    const resp = await fetch(`http://localhost:3005/products/${id}`, {
      method: "DELETE",
    });
}

这就是桌子:

<table border="1">
  <tr>
    <th>Product</th>
    <th>Title</th>
    <th>Price</th>
    <th>Options</th>
  </tr>
  <tr v-for="product in products" :title="product.description">
    <td><img :src="product.image" :alt="product.title"/></td>
    <td>{{ product.title }}</td>
    <td>{{ `${product.price}$` }}</td>
    <td>
      <button @click="toggleEdit(product._id)">edit</button> &nbsp
      <button @click="deleteProduct(product._id)">delete</button>
    </td>
  </tr>
</table>

【问题讨论】:

  • 我怀疑你必须调用填充products 的函数。 Vue 不知道 fetch 修改了后端的任何内容。

标签: javascript vue.js fetch-api vue-reactivity


【解决方案1】:

Vue 更新基于本地数据——它会跟踪你在组件中的数据,当它注意到它发生了变化时,它会更新渲染的组件以显示更改。

因此,当您调用服务器以删除 product,但不触摸本地组件中的 products 数组时,Vue 无法知道发生了什么变化。

要让 Vue 了解更改,您需要:

  1. 使用来自服务器的新副本刷新 products 列表
  2. 从服务器中删除相关产品后在本地手动删除它(可能我会选择)

无论哪种方式,您都会让 Vue 知道 products 列表中的更改,这是重要的部分。

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 1970-01-01
    • 2019-06-22
    • 2018-04-18
    • 1970-01-01
    • 2021-01-22
    • 2017-02-22
    • 2013-07-10
    • 1970-01-01
    相关资源
    最近更新 更多