You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vuetify自定义Datatable组件如何使用v-slot:item自定义操作列

问题原因

你在自定义Table组件标签上写的插槽默认是传递给Table组件本身的,没有透传给内部封装的<v-data-table>,所以对应插槽无法生效。

改造步骤

1. 修改自定义Table.vue代码

你需要在内部的v-data-table上添加插槽透传逻辑,同时可以在保留原有功能的基础上支持扩展顶部工具栏:

<template>
    <div>
        <v-data-table
            :headers="headers"
            :items="items"
            :search="search"
            :loading="loading"
            :items-per-page="itemsPerPage || 10"
            loading-text="Loading... Please wait"
            dense
            v-bind="$attrs"
        >
            <!-- 透传所有来自父组件的插槽到v-data-table -->
            <template v-for="(_, slotName) in $scopedSlots" v-slot:[slotName]="slotScope">
                <slot :name="slotName" v-bind="slotScope" />
            </template>
            
            <template v-slot:top>
                <v-toolbar dark flat dense>
                    <v-toolbar-title>{{ title }}</v-toolbar-title>
                    <v-spacer></v-spacer>
                    <v-text-field
                        v-model="search"
                        append-icon="mdi-magnify"
                        label="Search"
                        single-line
                        hide-details
                    ></v-text-field>
                    <v-spacer></v-spacer>
                    <!-- 预留顶部工具栏扩展插槽,方便父组件加新增按钮等 -->
                    <slot name="toolbar-extra"></slot>
                </v-toolbar>
            </template>
        </v-data-table>
    </div>
</template>

<script>
export default {
    name: "Table",
    props: [
        "headers",
        "items",
        "title",
        "itemsPerPage",
        "loading",
    ],
    inheritAttrs: false, // 避免原生属性挂到根div上,全部透传给v-data-table
    data: function () {
        return {
            search: '',
        }
    },
};
</script>

2. 配置表头添加操作列

在你传入Table组件的headers数组中添加操作列配置,不然表格不会渲染操作列:

// 你的headers数组示例
headers: [
    // 其他原有列配置
    { text: '操作', value: 'actions', sortable: false, align: 'center' }
]

3. 组件使用示例

改造完成后你就可以正常传递插槽实现自定义操作列和顶部工具栏扩展:

<Table
    :headers="headers"
    :items="groups"
    :loading="loading"
    title="Baseny"
    :items-per-page="5"
>
    <!-- 顶部工具栏扩展,放新增按钮 -->
    <template v-slot:toolbar-extra>
        <v-btn
            color="primary"
            :to="{ name: 'admin.times.create' }"
        >
            Dodaj zajęcie
        </v-btn>
    </template>
    
    <!-- 自定义操作列 -->
    <template v-slot:item.actions="{ item }">
        <v-icon
            small
            class="mr-2"
            @click="show(item)"
        >
            mdi-pool
        </v-icon>
        <v-icon
            small
            class="mr-2"
            @click="edit(item)"
        >
            mdi-pencil
        </v-icon>
    </template>
</Table>

内容的提问来源于stack exchange,提问作者Screeaam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:27:01