前往
大廳
主題

【隨手寫】Vue - Scoped Slots

wtfgn | 2024-01-02 21:57:43 | 巴幣 0 | 人氣 40

一下内容未必正確,請以官網内容爲準。
=============================================
原來scoped slots那麽有用之前都沒有發現到他,還一直想著如果有辦法從child component傳上去parent component就好了。
結果到今天才發現scoped slots這種東西(LOLLLL

基本上scoped slots就是把資料從child component傳上去parent component,讓parent component有更多的flexibility,同時parent component也要負責更多的東西,例如styling, formatting之類了。
=========================================================================
// App.vue
<template>
  <div>
    <data-table :columns="tableColumns" :data="tableData">
      <template v-slot:default="{ row, column }">
        <!-- Custom rendering based on the data and column -->
        <span v-if="column.key === 'name'">{{ row.name }}</span>
        <span v-else-if="column.key === 'age'">{{ row.age }}</span>
        <button v-else>Edit</button>
      </template>
    </data-table>
  </div>
</template>

<script setup>
import DataTable from './DataTable.vue';

const tableColumns = [
  { key: 'name', label: 'Name' },
  { key: 'age', label: 'Age' },
  { key: 'actions', label: 'Actions' }
];
const tableData = [
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 }
]
</script>
=========================================================================
// DataTable.vue
<template>
  <table>
    <thead>
      <tr>
        <th v-for="column in columns" :key="column.key">{{ column.label }}</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="row in data" :key="row.id">
        <td v-for="column in columns" :key="column.key">
          <slot :row="row" :column="column"></slot>
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script setup>
defineProps(['columns', 'data'])
</script>
=========================================================================
以上是一個簡單例子。
如果今天我們有一些資料,我們想要把他們放進一個表格裏面,也就是我們會在parent component(App.vue)傳那些資料到child component(DataTable.vue),而這個DataTable.vue就會是我們的表格。很自然地,我們會用到props,而tableColumns跟tableData就是我們要傳下去的props。

傳下去之後,我們就可以處理表格的樣式,例如直接把style寫在DataTable.vue裏面,不過這樣的做法並不理想,因爲如果我們有其他的資料,而我們想要不同樣式,這樣子我們就要重新再寫過一次DataTable.vue了。

這裏我們真正想要做的是,把資料傳進去DataTable.vue,然後這個組件就會根據資料弄一個表格出來,而那些表格就會再讓不同的parent component來去處理,這樣子我們就可以讓這個表格根據不同的需要而有所變化了,這個時候我們就要把DataTable.vue裏面接受了資料再傳出到parent component。這時候,scoped slots就很好用了。

如果想要看看效果的話,可以按一下這裏

創作回應

更多創作