Skip to content

Commit

Permalink
✨ feat:表格组件增加完善功能,更新表格组件文档,增加按钮公共组件的文档
Browse files Browse the repository at this point in the history
  • Loading branch information
autumnLeaves-lady committed Jan 16, 2024
1 parent c49c7fb commit 18a88c0
Show file tree
Hide file tree
Showing 7 changed files with 994 additions and 151 deletions.
37 changes: 16 additions & 21 deletions app/src/views/Table.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
:columns="columns"
:requestApi="getTableList"
:search-props="searchProps"
:pagination="false"
@update:checked-row-keys="handleCheck"
>
<!-- 表格header按钮 -->
Expand All @@ -16,10 +17,10 @@
</template>

<!-- 表格单元格 -->
<template #address="row">
<n-button type="primary">
{{ row.address }}
</n-button>
<template #address="row, index">
<n-tag type="primary">
{{ row.address + index }}
</n-tag>
</template>

<!-- 表格操作 -->
Expand All @@ -35,9 +36,9 @@

<script setup lang="tsx">
import { NaiveUiTable } from 'naive-ui-table'
import { NButton, NDataTable, NDrawer, NDrawerContent, NTooltip, useMessage } from 'naive-ui'
import { NButton, NTag, NDrawer, NDrawerContent, NTooltip, useMessage } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import type { Props } from 'naive-ui-form'
import type { Props as FormProps } from 'naive-ui-form'
const message = useMessage()
Expand All @@ -47,12 +48,7 @@ function handleCheck(param) {
}
// 搜索栏配置
const searchProps: Props = {
showExpandBtn: true,
grid: {
cols: 3,
xGap: 16
},
const searchProps: FormProps = {
schemas: [
{
label: '姓名',
Expand Down Expand Up @@ -111,11 +107,7 @@ const columns: DataTableColumns = [
key: 'name',
align: 'center',
render(row) {
return (
<NButton type="primary" onClick={() => console.log('我是通过 tsx 语法渲染的内容')}>
{row.name}
</NButton>
)
return <NTag type="warning">{row.name}</NTag>
}
},
{
Expand All @@ -142,15 +134,15 @@ const columns: DataTableColumns = [
{ title: '操作', key: 'operation', fixed: 'right', width: 330 }
]
// 如果你想在请求之前对当前请求参数做一些操作,可以自定义如下函数:params 为当前所有的请求参数(包括分页),最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定 :requestApi="getUserList"
async function getTableList(params: any) {
console.log('params: ', params)
// return Promise.reject('错误')
return await api(params)
}
function fun(type, row) {
message.info(type, row)
message.info(type)
console.log('row: ', row)
}
// 模拟接口请求
Expand All @@ -177,14 +169,17 @@ function api(params) {
params.current * params.size
)
setTimeout(() => {
// 不分页
// resolve(data)
// 分页
resolve({
current: params.current,
size: params.size,
pages: 5,
records,
total: allRecords.length
})
}, 1000)
}, 500)
})
}
</script>
Expand Down
68 changes: 47 additions & 21 deletions components/naive-ui-table/src/NaiveUiTable.vue
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
<!-- 设置 -->
<n-tooltip v-if="showToolButton('setting')">
<template #trigger>
<n-button circle @click="openDrawer">
<n-button circle @click="openDrawer(true)">
<template #icon>
<n-icon><SettingsOutline /></n-icon>
</template>
Expand All @@ -77,12 +77,12 @@
:loading="state.loading"
:pagination="newPagination"
:size="tableSize"
remote
:remote="tableRemote"
:single-line="false"
:row-key="(row) => row.id"
v-model:checked-row-keys="checkedRowKeys"
@update:checked-row-keys="handleCheck"
:max-height="maxHeight"
:max-height="height"
:scroll-x="scrollWidth"
v-bind="$attrs"
/>
Expand Down Expand Up @@ -127,17 +127,19 @@ defineOptions({
const props = withDefaults(defineProps<Props>(), {
columns: () => [],
requestAuto: true,
isPageApi: true,
pagination: true,
resizeHeightOffset: 25,
toolButton: true
toolButton: true,
remote: undefined
})
const emit = defineEmits(['update:checked-row-keys'])
/* 搜索表单ref */
const basicForm = ref<FormInstance | null>(null)
/* 控制 ToolButton 显示 */
/* 工具栏显隐 */
const showToolButton = (key: 'refresh' | 'size' | 'setting') => {
return Array.isArray(props.toolButton) ? props.toolButton.includes(key) : props.toolButton
}
Expand All @@ -157,7 +159,7 @@ const initColumns = ref(
item._show = true
if (item.render) return item
if (slot[item.key] && isFunction(slot[item.key])) {
item.render = (row) => (<Function>slot[item.key])(row)
item.render = slot[item.key]
}
return item
})
Expand All @@ -176,7 +178,7 @@ const tableColumns = computed(() => {
const { state, getTableList, handleSearch, handleReset, onUpdatePage, onUpdatePageSize } = useTable(
props.requestApi,
props.initParams,
props.pagination,
props.isPageApi,
props.dataCallback,
props.requestError,
basicForm
Expand All @@ -196,23 +198,47 @@ function refresh() {
/* 分页 */
const newPagination = computed(() => {
if (!props.pagination) return false
return {
page: state.pageAble.current,
pageSize: state.pageAble.size,
itemCount: state.pageAble.total,
pageSizes: PageSizes,
showSizePicker: true,
showQuickJumper: true,
prefix: (info) => `每页${info.pageSize}条,共${info.itemCount}条`,
onUpdatePage,
onUpdatePageSize
if (typeof props.pagination === 'object') return props.pagination
if (props.isPageApi) {
return {
page: state.pageAble.current,
pageSize: state.pageAble.size,
itemCount: state.pageAble.total,
pageSizes: PageSizes,
showSizePicker: true,
showQuickJumper: true,
prefix: (info) => `每页${info.pageSize}条,共${info.itemCount}条`,
onUpdatePage,
onUpdatePageSize
}
} else {
return {
page: state.pageAble.current,
pageSize: state.pageAble.size,
pageSizes: PageSizes,
showSizePicker: true,
prefix: (info) => `每页${info.pageSize}条,共${info.itemCount}条`,
onUpdatePage: (page: number) => {
state.pageAble.current = page
},
onUpdatePageSize: (pageSize: number) => {
state.pageAble.size = pageSize
state.pageAble.current = 1
}
}
}
})
/* 分页异步 */
const tableRemote = computed(() => {
if (typeof props.remote === 'boolean') return props.remote
return props.isPageApi
})
/* 打开列设置抽屉 */
const active = ref(false)
function openDrawer() {
active.value = true
function openDrawer(bool: boolean) {
active.value = bool
}
/* 勾选 */
Expand All @@ -225,7 +251,7 @@ function handleCheck(rowKeys: DataTableRowKey[], rows, meta) {
/* 表格高度 */
const tableRef = ref() // table 实例
const { tableMaxHeight } = useTableSize(tableRef, props.resizeHeightOffset)
const maxHeight = computed(() => {
const height = computed(() => {
return props.maxHeight || tableMaxHeight.value
})
Expand All @@ -244,7 +270,7 @@ defineExpose({
state,
tableColumns,
tableRef,
maxHeight,
height,
scrollWidth
})
</script>
Expand Down
28 changes: 19 additions & 9 deletions components/naive-ui-table/src/hooks/useTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import type { Props, FormInstance } from '../types'
export function useTable(
api: Props['requestApi'],
initParams: Props['initParams'],
isPage: Props['pagination'],
dataCallBack: Props['dataCallback'],
isPageApi: Props['isPageApi'],
dataCallback: Props['dataCallback'],
requestError: Props['requestError'],
basicForm: Ref<FormInstance | null>
) {
Expand All @@ -27,7 +27,7 @@ export function useTable(
state.loading = true
try {
// 分页参数
const pageParam = isPage
const pageParam = isPageApi
? {
[PageField]: state.pageAble.current,
[SizeField]: state.pageAble.size
Expand All @@ -39,19 +39,28 @@ export function useTable(

// 总参数
const totalParam = { ...initParams, ...pageParam, ...searchParam }
let res = await api(totalParam)
dataCallBack && (res = dataCallBack(res))
state.tableData = isPage ? res[ListField] : res
if (isPage) {
const filterParam = Object.fromEntries(
Object.entries(totalParam).filter(([_, v]) => v != null)
)
let res = await api(filterParam)
dataCallback && (res = dataCallback(res))
state.tableData = isPageApi ? res[ListField] : res
if (isPageApi) {
Object.assign(state.pageAble, {
current: res[PageField],
size: res[SizeField],
total: res[TotalField]
})
}
} catch (err) {
requestError && requestError(err)
} catch (err: any) {
closeLoading()
if (requestError) return requestError(err)
else throw new Error(err || '请求失败!')
}
closeLoading()
}

function closeLoading() {
state.loading = false
basicForm.value?.setLoading(false)
}
Expand All @@ -76,6 +85,7 @@ export function useTable(
// 每条页数改变
function onUpdatePageSize(pageSize: number) {
state.pageAble.size = pageSize
state.pageAble.current = 1
getTableList()
}

Expand Down
22 changes: 12 additions & 10 deletions components/naive-ui-table/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,18 @@ export type Recordable<T = any> = Record<string, T>

export type { FormInstance }
export interface Props {
columns: DataTableColumns<Recordable> // 列配置项 ==> 必传
columns: DataTableColumns<Recordable> // 列配置项
searchProps?: FormProps // 传给BasicForm的属性
requestApi?: (params: any) => Promise<any> // 请求表格数据的 api ==> 非必传
requestAuto?: boolean // 是否自动执行请求 api ==> 非必传(默认为true)
pagination?: boolean // 是否需要分页组件 ==> 非必传(默认为true)
maxHeight?: number | string // 表格最大高度 ==> 非必传
scrollX?: number // 表格横向宽度
resizeHeightOffset?: number // 表格底下留白距离 ==> 非必传(默认为0)
toolButton?: ('refresh' | 'size' | 'setting')[] | boolean // 是否显示表格功能按钮 ==> 非必传
requestApi?: (params: any) => Promise<any> // 请求表格数据的 api
requestAuto?: boolean // 是否自动执行请求 api(默认为true)
pagination?: boolean | object // 表格分页配置
isPageApi?: boolean // 接口是否为分页接口 (默认为true)
remote?: boolean // 是否异步
maxHeight?: number | string // 表格最大高度
scrollX?: number | string // 表格横向宽度
resizeHeightOffset?: number // 表格底下留白距离 (默认为0)
toolButton?: ('refresh' | 'size' | 'setting')[] | boolean // 是否显示表格功能按钮
initParams?: Recordable // 初始化请求参数 ==> 非必传(默认为{})
dataCallback?: (data: Recordable) => Recordable // 返回数据的回调函数,可以对数据进行处理 ==> 非必传
requestError?: (params: any) => void // 表格 api 请求错误监听 ==> 非必传
dataCallback?: (data: Recordable) => Recordable // 返回数据的回调函数,可以对数据进行处理
requestError?: (params: any) => void // 表格 api 请求错误监听
}
10 changes: 8 additions & 2 deletions docs/.vitepress/config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,15 @@ export default defineConfig({
{ text: 'naive-ui-editor', link: '/naive-ui-editor' },
{ text: 'naive-ui-table', link: '/naive-ui-table' },
{ text: 'naive-ui-editor-view', link: '/naive-ui-editor-view' },
{ text: 'naive-ui-ai-editor', link: '/naive-ui-ai-editor' }
{ text: 'naive-ui-ai-editor', link: '/naive-ui-ai-editor' },
{ text: '模板公共组件', items: [
{ text: 'Buttons', link: '/Buttons' },
] }
],

socialLinks: [{ icon: 'github', link: 'https://github.com/ashuicoder/naive-ui-components' }]
socialLinks: [{ icon: 'github', link: 'https://github.com/ashuicoder/naive-ui-components' }],
},
markdown:{
lineNumbers: true
}
})
Loading

0 comments on commit 18a88c0

Please sign in to comment.