iT邦幫忙

2025 iThome 鐵人賽

DAY 6
0
Vue.js

Vue 新手學習紀錄系列 第 6

Day 6|呈現詳細資訊

  • 分享至 

  • xImage
  •  

今天主要要做一個詳細資訊的呈現,整個資料呈現做完之後覺得把所有資訊放在一個表格裡面有點亂,所以想說試試看寫一個詳細資料呈現的方式,剛好會用到 Day4 所寫到的 props 和 emit。

新增 DetailModal.vue

在 src/components 中新增 DetailModal.vue,這也是主要放詳細資訊的地方

<template>
    <div v-if="visible" class="modal-overlay">
        <h3>{{ post?.pSchool }} {{ post?.pDep }}</h3>
        <button class="close" @click="close">×</button>
        <section class="content">
            <p><strong>年度:</strong>{{ post?.pYear }}</p>
            <p><strong>日期:</strong>{{ post?.pDate }}</p>

            <h4>背景 / 經歷</h4>
            <pre>{{ post?.pExp || '無' }}</pre>

            <h4>結果</h4>
            <pre>{{ post?.pResult1 || '無' }}</pre>

            <h4>來源</h4>
            <a v-if="post?.pURL" :href="post.pURL" target="_blank">查看 Dcard 原文</a>
        </section>
    </div>
</template>

<script setup>
    const props = defineProps({
        post: { type: Object, default: null },
        visible: { type: Boolean, default: false }
    });

    const emit = defineEmits(['close']);;
    function close() {
        emit('close');
    };
</script>

在這邊使用到 props 是因為父元件控制了 visible 和 post,父元件控制了要不要打開和需要傳哪筆資料,因此才會使用到 props。而使用到 emit 是因為子元件要告訴父元件需要關閉詳細資訊面板,這時候父元件會再把 showModal 設成 false。

PostTable.vue 中的改動

在 PostTable.vue 中改為點選那一欄會打開相對應的詳細資訊

<tr v-for="post in posts" :key="post.pId" @click="$emit('select', post)">
    <td>{{ post.pSchool }}</td>
    <td>{{ post.pDep }}</td>
    <td>{{ post.pYear }}</td>
    <td>{{ post.pDate }}</td>
    <td>{{ post.pScore ?? '-' }}</td>
    <td>{{ post.pResult1 }}</td>
    <td>
        <a v-if="post.pURL" :href="post.pURL" target="_blank">來源</a>
    </td>
</tr>

在 App.vue 中監聽 Modal 狀態

import DetailModal from './components/DetailModal.vue'
...

const selectedPost = ref(null)
const showModal = ref(false)

function openDetail(post) {
  selectedPost.value = post
  showModal.value = true
}

...
</script>

<template>
  <Header />
  <main>
    ...
    <PostTable :posts="filteredPosts" v-if="filteredPosts.length > 0" @select="openDetail"/>
    <p v-else>查無相關結果 QQ</p>
    <DetailModal :visible="showModal" :post="selectedPost" @close="showModal=false" />
  </main>
</template>

有成功用出相對應的詳細面板,但是太醜了就不放了ww 我要美化去了


上一篇
Day 5|Computed + filter 製作簡易搜尋功能
下一篇
Day 7|分頁 Pagination
系列文
Vue 新手學習紀錄9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言