Javascript Filter in options & composition

Vue3 的寫法有兩種方式 options & composition,官方建議是採用 composition,在 Vue3 一般 CRUD 中的刪除作業 (Delete),當後端資料刪除後,在前端的顯示可以有兩種作法,一是由後端重新取得資料送往前端,二是在前端直接篩選掉被刪除的資料即可。

若是選擇第二種方式,可以使用 Javascript 的 filter,在 options 與 composition 的寫法分別如下:

<template>
  <div>
      <table class="table">
          <thead>
            <tr>
              <th scope="col">#</th>
              <th scope="col">Name</th>
              <th scope="col">Description</th>
              <th scope="col">Price</th>
              <th scope="col">Actions</th>
            </tr>
          </thead>
          <tbody>
              <tr v-for="merchandise in merchandises" :key="merchandise.id">
                  <td>{{ merchandise.id }}</td>
                  <td>{{ merchandise.name }}</td>
                  <td>{{ merchandise.description }}</td>
                  <td>{{ merchandise.price }}</td>
                  <td>
                    <div class="row gap-3">
                      <router-link :to="`/merchandises/${merchandise.id}`" class="p-2 col border btn btn-primary">View</router-link>
                      <router-link :to="`/merchandises/${merchandise.id}/edit`" class="p-2 col border btn btn-success">Edit</router-link>
                      <button @click="deleteMerchandise(merchandise.id)" type="button" class="p-2 col border btn btn-danger">Delete</button>
                    </div>
                  </td>
              </tr>
          </tbody>
      </table>
  </div>
</template>

<script>
import { apiClient } from '@/axios';

export default {
data() {
  return {
    merchandises: []
  }
},
async created() {
  try {
    const response = await apiClient.get('/merchandises');
    this.merchandises = response.data.result;
  } catch (error) {
    console.error(error);
  }
},
methods: {
  async deleteMerchandise(id) {
    try {
      await apiClient.delete(`/merchandises/${id}`);
      this.merchandises = this.merchandises.filter(merchandise => merchandise.id !== id);
    } catch (error) {
      console.error(error);
    }
  }
}
}
</script>

若是用 composition 則如下

<script setup>
import { apiClient } from '@/axios';
import { ref, onMounted } from 'vue';

const merchandises= ref([]);
const deleteMerchandise = async (id) => {
    console.log(userData);
    try {
        await apiClient.delete(`/merchandises/${id}`);
        merchandises.value = merchandises.value.filter( merchandise=> merchandise.id!==id);
    } catch (error) {
        console.error(error);
    }
    toast.add({ severity: 'warn', summary: t('toast.warn'), detail: userData, life: 3000 });
}
</script>

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *