今天主要要做一個詳細資訊的呈現,整個資料呈現做完之後覺得把所有資訊放在一個表格裡面有點亂,所以想說試試看寫一個詳細資料呈現的方式,剛好會用到 Day4 所寫到的 props 和 emit。
在 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 中改為點選那一欄會打開相對應的詳細資訊
<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>
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 我要美化去了