Naive UI的表格组件跟Element UI有点不同,template里面不需要再写每一列的组件,而是通过数组渲染每一列的数据。
<template>
<n-data-table
:columns="columns"
:data="data"
:pagination="pagination"
:bordered="false"
/>
</template>
<script lang="ts">
import { h, defineComponent } from 'vue'
import { NButton, useMessage } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
type Song = {
no: number
title: string
length: string
}
const createColumns = ({
play
}: {
play: (row: Song) => void
}): DataTableColumns<Song> => {
return [
{
title: 'No',
key: 'no'
},
{
title: 'Title',
key: 'title'
},
{
title: 'Length',
key: 'length'
},
{
title: 'Action',
key: 'actions',
render (row) {
return h(
NButton,
{
strong: true,
tertiary: true,
size: 'small',
onClick: () => play(row)
},
{ default: () => 'Play' }
)
}
}
]
}
const data: Song[] = [
{ no: 3, title: 'Wonderwall', length: '4:18' },
{ no: 4, title: "Don't Look Back in Anger", length: '4:48' },
{ no: 12, title: 'Champagne Supernova', length: '7:27' }
]
export default defineComponent({
setup () {
const message = useMessage()
return {
data,
columns: createColumns({
play (row: Song) {
message.info(`Play ${row.title}`)
}
}),
pagination: false as const
}
}
})
</script>
刚好遇到一个需求,要根据不同状态,显示隐藏不同列,所以要动态修改columns属性的数组,看到官方githup仓库上也有这么个issue:但目前最新版本也并没有支持这个属性。能否针对 data-table 组件 增加列的显示隐藏属性? · Issue #5278 · tusen-ai/naive-ui · GitHub
下面提供一个思路,使用计算属性,动态控制某一列的显示和隐藏:
// 构建数据表格列
const columns = computed(() => {
const { state } = params.value
const cols: DataTableColumns<item> = [
{
title: '序号',
minWidth: 55,
key: 'index',
render: (_, index) => {
return `${index + 1 + (params.value.currentPage - 1) * params.value.size}`
}
},
{
title: '姓名',
key: 'name',
minWidth: 100
},
{
title: '开始时间',
key: 'createTime',
minWidth: 175
},
{
title: '结束时间',
key: 'finishTime',
minWidth: state !== 'Cancel' ? 175 : 0
},
{
title: '记录条数',
key: 'count',
minWidth: state === 'Finish' ? 115 : 0,
},
{
title: '费用/元',
key: 'fee',
minWidth: 90
},
{
title: '原因',
key: 'reason',
minWidth: state === 'Refuse' ? 200 : 0
}
]
// 动态切换状态后,要动态隐藏的列,把宽度或最小宽度设置为0 ,再进行过滤
return cols.filter(i => i.width || i.minWidth)
})
通过控制width属性,再过滤掉宽度为0的列,就可以动态切换表格每一列的显示和隐藏。