口袋餐廳頁面下方區塊是篩選後的清單,以表單形式顯示所選的口袋餐廳。畫面示意圖請參考「Day14-試試Vue3-規劃口袋餐廳的頁面」篇。
(1)口袋餐廳清單-主表
分為資料渲染與觸發時機兩部分說明。
1.清單內容
口袋餐廳清單(以下簡稱口袋清單)使用 v-for="item in userResList" 將會員餐廳 API 進行多筆資料渲染。
2.導出的資料增加屬性<script></script> 中資料實體增加屬性 userResList 存放會員餐廳 API 取得的資料(會員名稱、電子郵件、口袋餐廳清單)。屬性有 name、email、userRestaurants(底下有 brandName 、 address 、 type 屬性)。
3.觸發時機
<template>
  ...
  <table class="table table-bordered">
    <thead>
      <tr>
        <th scope="col" class="table-secondary">品牌受眾</th>
        <th scope="col" class="table-secondary">品牌名稱</th>
        <th scope="col" class="table-secondary">地址</th>
        <th scope="col" class="table-warning">動作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="item in userResList" v-bind:key="item">
        <td>{{ item.type }}</td>
        <td>{{ item.brandName }}</td>
        <td>{{ item.address }}</td>
        <td class="table-warning">
          <button type="button">移除</button>
        </td>
      </tr>
    </tbody>
  </table>
  ...
</template>
<script>
...
export default {
  data() {
    return {
      restaurants: [],
      userResList: [],
      ...
      apiUserResUrl: "",
      ...
    };
  }
...
  methods: {
    ...
    userPocket() {
      axios
        .get(this.apiUserResUrl)
        .then((res) => {
          console.log(res);
          // 將會員餐廳取得的資料賦值給既有restaurants
          this.userResList = res.data[0].userRestaurants;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    ...
    submitPucket() {
      event.preventDefault();
      if (
        (this.saveRes.saveBrandName !== "") &
        (this.saveRes.saveAddress !== "") &
        (this.saveRes.saveType !== "")
      ) {
        axios
          .get(this.apiUserResUrl)
          .then((res) => {
            ...
            const newRestaurant ...
            // 使用陣列方法 some 檢查會員餐廳API是否有已存在的brandName
            const exists ...
            if (!exists) {
              userData.userRestaurants.push(newRestaurant);
              alert("口袋添加成功");
              axios.put(this.apiUserResIdUrl, userData);
              this.userPocket();
            } else {
              alert("該餐廳已存在!");
            }
          })
          .catch((error) => {
            console.log(error);
            alert("口袋添加失敗");
          });
      } else {
        alert("欄位不可空值!");
      }
    },
  },
  ...
  mounted() {
    ...
    this.userPocket();
  },
  ...
};
</script>