用 div v‐for 顯示資料 - daniel-qa/Vue GitHub Wiki

用 div + v-for 顯示資料

  • 顯示學校清單,有按鍵
<template>
    <div class="menu-container">
        <div class="menu-item"
             v-for="school in schoolList"
             :key="school.id"
             :class="{ active: selectedSchoolId === school.id }">
            <span @click="selectSchool(school.id)">
                {{ school.name }}
            </span>
            <button class="menu-button"
                    @click.stop="handleButtonClick(school.id)">
                點擊
            </button>
        </div>
    </div>
</template>

<script setup>
    import { ref } from "vue";

    // 學校資料
    const schoolList = ref([
        { id: 1, name: "School A" },
        { id: 2, name: "School B" },
        { id: 3, name: "School C" },
    ]);

    // 記錄選擇的學校
    const selectedSchoolId = ref(null);

    // 選擇學校的函式
    const selectSchool = (id) => {
        selectedSchoolId.value = id;
    };

    // 按鈕的處理函式
    const handleButtonClick = (id) => {
        alert(`按鈕被點擊!學校 ID:${id}`);
    };
</script>

<style scoped>
    .menu-container {
        display: flex;
        flex-direction: column;
        width: 300px;
        border: 1px solid #ccc;
        border-radius: 4px;
        background: #f9f9f9;
        overflow: hidden;
    }

    .menu-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 15px;
        border-bottom: 1px solid #eee;
        cursor: pointer;
        transition: background-color 0.3s;
    }

        .menu-item:last-child {
            border-bottom: none;
        }

        .menu-item:hover {
            background-color: #f0f0f0;
        }

        .menu-item.active span {
            font-weight: bold;
            color: #007bff;
        }

    .menu-button {
        margin-left: 10px;
        padding: 5px 10px;
        border: none;
        background-color: #007bff;
        color: white;
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.3s;
    }

        .menu-button:hover {
            background-color: #0056b3;
        }
</style>
⚠️ **GitHub.com Fallback** ⚠️