簡體   English   中英

刪除項目后重新渲染表格

[英]Re-render table after deleting item

我正在嘗試創建一個顯示來自服務器的數據的表。 刪除方法有效,但只有在刷新頁面后才會顯示在表格上。 刪除項目后如何強制組件重新渲染? 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>

Vue 更新基於本地數據——它跟蹤你在組件中的數據,當它注意到它發生了變化時,它會更新渲染的組件以顯示更改。

所以,當你調用你的服務器來刪除一個product ,但沒有觸及你本地組件中的products數組時,Vue 無法知道任何東西都發生了變化。

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

  1. 使用來自服務器的新副本刷新products列表
  2. 從服務器中刪除相關產品后在本地手動刪除它(可能是我選擇的)

無論哪種方式,您都會讓 Vue 了解products列表中的更改,這是重要的部分。

也許你應該像這樣更新數據

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

async getProducts() {
  const res = await apiCall.....
  this.products = res.data;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM