沛縣做網(wǎng)站xlec中國關(guān)鍵詞網(wǎng)站
前言
一般情況table列表的展示,列頭都在第一橫行,此方法用于列頭在第一列的情況。
效果圖
核心代碼
<template><div><table class="data-table"><tr v-for="(column, columnIndex) in columns" :key="'column-' + columnIndex"><th class="header-cell">{{ column }}</th><td v-for="(row, rowIndex) in data" :key="'row-' + rowIndex" style="border: 1px solid black;"><!-- 如果當(dāng)前列是"name", 則顯示一個(gè)帶有名字的按鈕 --><div v-if="column === 'name'">{{ row[column] }}<button type="button" @click="handleButtonClick">Click Me</button></div><!-- 如果當(dāng)前列是 "image", 顯示圖片 --><img v-else-if="column === 'image'" :src="row[column]" alt="Image" /><span v-else>{{ row[column] }}</span></td></tr></table></div>
</template>
<script>
export default {data () {return {// 一般為后端接收數(shù)據(jù),視情況而定data: [{ name: 'a', age: '1', image: 'https://example.com/image1.png' },{ name: 'b', age: '2', image: 'https://example.com/image2.png' },{ name: 'c', age: '3', image: 'https://example.com/image3.png' },// 更多數(shù)據(jù)...],columns: ['name', 'age', 'image'],};},methods: {handleButtonClick() {alert('Button clicked!');},},
};
</script>
<style scoped>
.data-table {border-collapse: collapse; /* 刪除邊框之間的間距 */width: 100%; /* 表格全寬 */max-width: 600px; /* 最大寬度 */margin: 0 auto; /* 水平居中 */background-color: #ddd;color: black;
}.header-cell,
.data-cell {border: 1px solid #ddd; /* 單元格邊框 */padding: 8px; /* 單元格內(nèi)邊距 */text-align: left; /* 文本左對(duì)齊 */
}.header-cell {background-color: blanchedalmond; /* 表頭背景 */font-weight: bold; /* 表頭字體加粗 */color: black;
}
</style>
核心邏輯
首先,我們使用 Vue 的 `v-for` 指令來遍歷我們的數(shù)據(jù),分別創(chuàng)建行 `column` 和列 `row`。每個(gè) <th> 標(biāo)簽用于表示頭部單元格,而每個(gè) <td> 標(biāo)簽為表格的數(shù)據(jù)單元格。最關(guān)鍵的部分是,我們要在每個(gè) <td> 標(biāo)簽中加入邏輯判斷,根據(jù)不同的列 "column",展示不同的格式。在這個(gè)示例中,我們對(duì) "name", "age" 和 "image" 三種列進(jìn)行了處理:- 對(duì)于 "name" 列, 我們在顯示名稱數(shù)據(jù)后還附加了一個(gè)按鈕,按鈕點(diǎn)擊后會(huì)調(diào)用 `handleButtonClick` 方法進(jìn)行對(duì)應(yīng)操作;
- 對(duì)于 "image" 列, 我們使用了 `v-else-if` 指令,此處我們顯示一個(gè)對(duì)應(yīng)的圖片,圖片鏈接為該行 "image" 列的數(shù)據(jù);
- 對(duì)于其他列,我們直接展示列中的數(shù)據(jù)。