提交 72b42d7b 作者: Vben

feat(tree): add renderIcon props close #309

上级 d67bd496
...@@ -11,6 +11,7 @@ ...@@ -11,6 +11,7 @@
- 新增修改密码界面 - 新增修改密码界面
- 新增部门管理示例界面 - 新增部门管理示例界面
- 新增 WebSocket 示例和服务脚本 - 新增 WebSocket 示例和服务脚本
- BasicTree 组件新增 `renderIcon` 属性用于控制层级图标显示
### ⚡ Performance Improvements ### ⚡ Performance Improvements
......
import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent'; import BasicTree from './src/index.vue';
export const BasicTree = createAsyncComponent(() => import('./src/BasicTree'));
export { BasicTree };
export type { ContextMenuItem } from '/@/hooks/web/useContextMenu'; export type { ContextMenuItem } from '/@/hooks/web/useContextMenu';
export * from './src/types'; export * from './src/types';
import type { VNode, FunctionalComponent } from 'vue';
import { h } from 'vue';
import { isString } from '/@/utils/is';
import { Icon } from '/@/components/Icon';
export interface ComponentProps {
icon: VNode | string;
}
export const TreeIcon: FunctionalComponent = ({ icon }: ComponentProps) => {
if (!icon) return null;
if (isString(icon)) {
return h(Icon, { icon, class: 'mr-1' });
}
return Icon;
};
.basic-tree {
position: relative;
&-title {
position: relative;
display: inline-block;
width: 100%;
padding-right: 10px;
&:hover {
.basic-tree__action {
visibility: visible;
}
}
}
&__content {
display: inline-block;
overflow: hidden;
}
&__actions {
position: absolute;
top: 0;
right: 0;
display: flex;
}
&__action {
margin-left: 4px;
// float: right;
// display: none;
visibility: hidden;
}
}
import './index.less'; <script lang="tsx">
import type { ReplaceFields, Keys, CheckKeys, TreeActionType, TreeItem } from './types';
import type { ReplaceFields, TreeItem, Keys, CheckKeys, TreeActionType } from './types'; import { defineComponent, reactive, computed, unref, ref, watchEffect, onMounted } from 'vue';
import { Tree } from 'ant-design-vue';
import { TreeIcon } from './TreeIcon';
// import { DownOutlined } from '@ant-design/icons-vue';
import { defineComponent, reactive, computed, unref, ref, watchEffect, CSSProperties } from 'vue'; import { omit, get } from 'lodash-es';
import { Tree } from 'ant-design-vue'; import { isFunction } from '/@/utils/is';
import { DownOutlined } from '@ant-design/icons-vue'; import { extendSlots } from '/@/utils/helper/tsxHelper';
import { useContextMenu, ContextMenuItem } from '/@/hooks/web/useContextMenu'; import { useTree } from './useTree';
import { useContextMenu, ContextMenuItem } from '/@/hooks/web/useContextMenu';
import { useExpose } from '/@/hooks/core/useExpose';
import { useDesign } from '/@/hooks/web/useDesign';
import { isFunction } from '/@/utils/is'; import { basicProps } from './props';
import { omit } from 'lodash-es';
import { extendSlots } from '/@/utils/helper/tsxHelper';
import { basicProps } from './props'; interface State {
import { useTree } from './useTree';
import { useExpose } from '/@/hooks/core/useExpose';
import { onMounted } from 'vue';
interface State {
expandedKeys: Keys; expandedKeys: Keys;
selectedKeys: Keys; selectedKeys: Keys;
checkedKeys: CheckKeys; checkedKeys: CheckKeys;
} }
const prefixCls = 'basic-tree'; export default defineComponent({
export default defineComponent({
name: 'BasicTree', name: 'BasicTree',
props: basicProps, props: basicProps,
emits: ['update:expandedKeys', 'update:selectedKeys', 'update:value', 'get'], emits: ['update:expandedKeys', 'update:selectedKeys', 'update:value', 'get'],
...@@ -37,6 +36,7 @@ export default defineComponent({ ...@@ -37,6 +36,7 @@ export default defineComponent({
const treeDataRef = ref<TreeItem[]>([]); const treeDataRef = ref<TreeItem[]>([]);
const [createContextMenu] = useContextMenu(); const [createContextMenu] = useContextMenu();
const { prefixCls } = useDesign('basic-tree');
const getReplaceFields = computed( const getReplaceFields = computed(
(): Required<ReplaceFields> => { (): Required<ReplaceFields> => {
...@@ -50,15 +50,15 @@ export default defineComponent({ ...@@ -50,15 +50,15 @@ export default defineComponent({
} }
); );
const getContentStyle = computed( // const getContentStyle = computed(
(): CSSProperties => { // (): CSSProperties => {
const { actionList } = props; // const { actionList } = props;
const width = actionList.length * 18; // const width = actionList.length * 18;
return { // return {
width: `calc(100% - ${width}px)`, // width: `calc(100% - ${width}px)`,
}; // };
} // }
); // );
const getBindValues = computed(() => { const getBindValues = computed(() => {
let propsData = { let propsData = {
...@@ -77,8 +77,9 @@ export default defineComponent({ ...@@ -77,8 +77,9 @@ export default defineComponent({
state.selectedKeys = v; state.selectedKeys = v;
emit('update:selectedKeys', v); emit('update:selectedKeys', v);
}, },
onCheck: (v: CheckKeys) => { onCheck: (v: CheckKeys, e) => {
state.checkedKeys = v; state.checkedKeys = v;
console.log(e);
emit('update:value', v); emit('update:value', v);
}, },
onRightClick: handleRightClick, onRightClick: handleRightClick,
...@@ -94,12 +95,18 @@ export default defineComponent({ ...@@ -94,12 +95,18 @@ export default defineComponent({
getReplaceFields getReplaceFields
); );
// 渲染操作按钮 function getIcon(params: Recordable, icon?: string) {
if (!icon) {
if (props.renderIcon && isFunction(props.renderIcon)) {
return props.renderIcon(params);
}
}
return icon;
}
function renderAction(node: TreeItem) { function renderAction(node: TreeItem) {
const { actionList } = props; const { actionList } = props;
if (!actionList || actionList.length === 0) return; if (!actionList || actionList.length === 0) return;
return actionList.map((item, index) => { return actionList.map((item, index) => {
return ( return (
<span key={index} class={`${prefixCls}__action`}> <span key={index} class={`${prefixCls}__action`}>
...@@ -108,8 +115,8 @@ export default defineComponent({ ...@@ -108,8 +115,8 @@ export default defineComponent({
); );
}); });
} }
// 渲染树节点
function renderTreeNode({ data }: { data: TreeItem[] | undefined }) { function renderTreeNode({ data, level }: { data: TreeItem[] | undefined; level: number }) {
if (!data) { if (!data) {
return null; return null;
} }
...@@ -117,30 +124,36 @@ export default defineComponent({ ...@@ -117,30 +124,36 @@ export default defineComponent({
const { title: titleField, key: keyField, children: childrenField } = unref( const { title: titleField, key: keyField, children: childrenField } = unref(
getReplaceFields getReplaceFields
); );
const propsData = omit(item, 'title'); const propsData = omit(item, 'title');
const anyItem = item as any; const icon = getIcon({ ...item, level }, item.icon);
return ( return (
<Tree.TreeNode {...propsData} key={anyItem?.[keyField]}> <Tree.TreeNode {...propsData} key={get(item, keyField)}>
{{ {{
title: () => ( title: () => (
<span class={`${prefixCls}-title`}> <span class={`${prefixCls}-title`}>
<span class={`${prefixCls}__content`} style={unref(getContentStyle)}> {icon && <TreeIcon icon={icon} />}
{titleField && anyItem[titleField]} <span
class={`${prefixCls}__content`}
// style={unref(getContentStyle)}
>
{get(item, titleField)}
</span> </span>
<span class={`${prefixCls}__actions`}> {renderAction(item)}</span> <span class={`${prefixCls}__actions`}> {renderAction(item)}</span>
</span> </span>
), ),
default: () => renderTreeNode({ data: childrenField ? anyItem[childrenField] : [] }), default: () =>
renderTreeNode({ data: get(item, childrenField) || [], level: level + 1 }),
}} }}
</Tree.TreeNode> </Tree.TreeNode>
); );
}); });
} }
// 处理右键事件
async function handleRightClick({ event, node }: any) { async function handleRightClick({ event, node }: any) {
const { rightMenuList: menuList = [], beforeRightClick } = props; const { rightMenuList: menuList = [], beforeRightClick } = props;
let rightMenuList: ContextMenuItem[] = []; let rightMenuList: ContextMenuItem[] = [];
if (beforeRightClick && isFunction(beforeRightClick)) { if (beforeRightClick && isFunction(beforeRightClick)) {
rightMenuList = await beforeRightClick(node); rightMenuList = await beforeRightClick(node);
} else { } else {
...@@ -206,14 +219,63 @@ export default defineComponent({ ...@@ -206,14 +219,63 @@ export default defineComponent({
return () => { return () => {
return ( return (
<Tree {...(unref(getBindValues) as any)} class={prefixCls}> <Tree {...unref(getBindValues)} showIcon={false} class={[prefixCls]}>
{{ {{
switcherIcon: () => <DownOutlined />, // switcherIcon: () => <DownOutlined />,
default: () => renderTreeNode({ data: unref(getTreeData) }), default: () => renderTreeNode({ data: unref(getTreeData), level: 1 }),
...extendSlots(slots), ...extendSlots(slots),
}} }}
</Tree> </Tree>
); );
}; };
}, },
}); });
</script>
<style lang="less">
@prefix-cls: ~'@{namespace}-basic-tree';
.@{prefix-cls} {
position: relative;
.ant-tree-node-content-wrapper {
position: relative;
.ant-tree-title {
position: absolute;
left: 0;
width: 100%;
}
}
&-title {
position: relative;
display: flex;
align-items: center;
width: 100%;
padding-right: 10px;
&:hover {
.@{prefix-cls}__action {
visibility: visible;
}
}
}
&__content {
display: inline-block;
overflow: hidden;
}
&__actions {
position: absolute;
top: 2px;
right: 2px;
display: flex;
}
&__action {
margin-left: 4px;
visibility: hidden;
}
}
</style>
import { PropType } from 'vue'; import type { PropType } from 'vue';
import type { ReplaceFields, TreeItem, ActionItem, Keys, CheckKeys } from './types'; import type { ReplaceFields, ActionItem, Keys, CheckKeys } from './types';
import type { ContextMenuItem } from '/@/hooks/web/useContextMenu'; import type { ContextMenuItem } from '/@/hooks/web/useContextMenu';
import type { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
export const basicProps = { export const basicProps = {
renderIcon: {
type: Function as PropType<(params: Recordable) => string>,
},
replaceFields: { replaceFields: {
type: Object as PropType<ReplaceFields>, type: Object as PropType<ReplaceFields>,
}, },
treeData: { treeData: {
type: Array as PropType<TreeItem[]>, type: Array as PropType<TreeDataItem[]>,
}, },
actionList: { actionList: {
...@@ -50,7 +54,7 @@ export const treeNodeProps = { ...@@ -50,7 +54,7 @@ export const treeNodeProps = {
type: Object as PropType<ReplaceFields>, type: Object as PropType<ReplaceFields>,
}, },
treeData: { treeData: {
type: Array as PropType<TreeItem[]>, type: Array as PropType<TreeDataItem[]>,
default: () => [], default: () => [],
}, },
}; };
import type { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
export interface ActionItem { export interface ActionItem {
render: (record: any) => any; render: (record: any) => any;
} }
export interface TreeItem { export interface TreeItem extends TreeDataItem {
/**
* Class
* @description className
* @type string
*/
class?: string;
/**
* Style
* @description style of tree node
* @type string | object
*/
style?: string | object;
/**
* Disable Checkbox
* @description Disables the checkbox of the treeNode
* @default false
* @type boolean
*/
disableCheckbox?: boolean;
/**
* Disabled
* @description Disabled or not
* @default false
* @type boolean
*/
disabled?: boolean;
/**
* Icon
* @description customize icon. When you pass component, whose render will receive full TreeNode props as component props
* @type any (slot | slot-scope)
*/
icon?: any; icon?: any;
/**
* Is Leaf?
* @description Leaf node or not
* @default false
* @type boolean
*/
isLeaf?: boolean;
/**
* Key
* @description Required property, should be unique in the tree
* (In tree: Used with (default)ExpandedKeys / (default)CheckedKeys / (default)SelectedKeys)
* @default internal calculated position of treeNode or undefined
* @type string | number
*/
key: string | number;
/**
* Selectable
* @description Set whether the treeNode can be selected
* @default true
* @type boolean
*/
selectable?: boolean;
/**
* Title
* @description Content showed on the treeNodes
* @default '---'
* @type any (string | slot)
*/
title: any;
/**
* Value
* @description Will be treated as treeNodeFilterProp by default, should be unique in the tree
* @default undefined
* @type string
*/
value?: string;
children?: TreeItem[];
slots?: any;
scopedSlots?: any;
} }
export interface ReplaceFields { export interface ReplaceFields {
...@@ -107,12 +29,12 @@ export interface TreeActionType { ...@@ -107,12 +29,12 @@ export interface TreeActionType {
filterByLevel: (level: number) => void; filterByLevel: (level: number) => void;
insertNodeByKey: (opt: InsertNodeParams) => void; insertNodeByKey: (opt: InsertNodeParams) => void;
deleteNodeByKey: (key: string) => void; deleteNodeByKey: (key: string) => void;
updateNodeByKey: (key: string, node: Omit<TreeItem, 'key'>) => void; updateNodeByKey: (key: string, node: Omit<TreeDataItem, 'key'>) => void;
} }
export interface InsertNodeParams { export interface InsertNodeParams {
parentKey: string | null; parentKey: string | null;
node: TreeItem; node: TreeDataItem;
list?: TreeItem[]; list?: TreeDataItem[];
push?: 'push' | 'unshift'; push?: 'push' | 'unshift';
} }
import type { InsertNodeParams, ReplaceFields, TreeItem } from './types'; import type { InsertNodeParams, ReplaceFields } from './types';
import type { Ref, ComputedRef } from 'vue'; import type { Ref, ComputedRef } from 'vue';
import type { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
import { cloneDeep } from 'lodash-es'; import { cloneDeep } from 'lodash-es';
import { unref } from 'vue'; import { unref } from 'vue';
import { forEach } from '/@/utils/helper/treeHelper'; import { forEach } from '/@/utils/helper/treeHelper';
export function useTree( export function useTree(
treeDataRef: Ref<TreeItem[]>, treeDataRef: Ref<TreeDataItem[]>,
getReplaceFields: ComputedRef<ReplaceFields> getReplaceFields: ComputedRef<ReplaceFields>
) { ) {
// 更新节点 // Update node
function updateNodeByKey(key: string, node: TreeItem, list?: TreeItem[]) { function updateNodeByKey(key: string, node: TreeDataItem, list?: TreeDataItem[]) {
if (!key) return; if (!key) return;
const treeData = list || unref(treeDataRef); const treeData = list || unref(treeDataRef);
const { key: keyField, children: childrenField } = unref(getReplaceFields); const { key: keyField, children: childrenField } = unref(getReplaceFields);
...@@ -30,8 +31,8 @@ export function useTree( ...@@ -30,8 +31,8 @@ export function useTree(
} }
} }
// 展开指定级别 // Expand the specified level
function filterByLevel(level = 1, list?: TreeItem[], currentLevel = 1) { function filterByLevel(level = 1, list?: TreeDataItem[], currentLevel = 1) {
if (!level) { if (!level) {
return []; return [];
} }
...@@ -74,8 +75,8 @@ export function useTree( ...@@ -74,8 +75,8 @@ export function useTree(
treeDataRef.value = treeData; treeDataRef.value = treeData;
} }
// 删除节点 // Delete node
function deleteNodeByKey(key: string, list?: TreeItem[]) { function deleteNodeByKey(key: string, list?: TreeDataItem[]) {
if (!key) return; if (!key) return;
const treeData = list || unref(treeDataRef); const treeData = list || unref(treeDataRef);
const { key: keyField, children: childrenField } = unref(getReplaceFields); const { key: keyField, children: childrenField } = unref(getReplaceFields);
......
...@@ -35,6 +35,7 @@ ...@@ -35,6 +35,7 @@
setup() { setup() {
const treeRef = ref<Nullable<TreeActionType>>(null); const treeRef = ref<Nullable<TreeActionType>>(null);
const { createMessage } = useMessage(); const { createMessage } = useMessage();
function getTree() { function getTree() {
const tree = unref(treeRef); const tree = unref(treeRef);
if (!tree) { if (!tree) {
......
<template> <template>
<PageWrapper title="Tree函数操作示例"> <PageWrapper title="Tree函数操作示例">
<div class="flex"> <div class="flex">
<CollapseContainer title="右侧操作按钮" class="mr-4" :style="{ width: '33%' }"> <CollapseContainer title="右侧操作按钮/自定义图标" class="mr-4" :style="{ width: '33%' }">
<BasicTree :treeData="treeData" :actionList="actionList" /> <BasicTree :treeData="treeData" :actionList="actionList" :renderIcon="createIcon" />
</CollapseContainer> </CollapseContainer>
<CollapseContainer title="右键菜单" class="mr-4" :style="{ width: '33%' }"> <CollapseContainer title="右键菜单" class="mr-4" :style="{ width: '33%' }">
...@@ -61,7 +61,19 @@ ...@@ -61,7 +61,19 @@
}, },
}, },
]; ];
return { treeData, actionList, getRightMenuList };
function createIcon({ level }) {
if (level === 1) {
return 'ion:git-compare-outline';
}
if (level === 2) {
return 'ion:home';
}
if (level === 3) {
return 'ion:airplane';
}
}
return { treeData, actionList, getRightMenuList, createIcon };
}, },
}); });
</script> </script>
...@@ -2,9 +2,8 @@ import { TreeItem } from '/@/components/Tree/index'; ...@@ -2,9 +2,8 @@ import { TreeItem } from '/@/components/Tree/index';
export const treeData: TreeItem[] = [ export const treeData: TreeItem[] = [
{ {
title: 'parent 1parent ', title: 'parent ',
key: '0-0', key: '0-0',
icon: 'home|svg',
children: [ children: [
{ title: 'leaf', key: '0-0-0' }, { title: 'leaf', key: '0-0-0' },
{ {
...@@ -20,7 +19,6 @@ export const treeData: TreeItem[] = [ ...@@ -20,7 +19,6 @@ export const treeData: TreeItem[] = [
{ {
title: 'parent 2', title: 'parent 2',
key: '1-1', key: '1-1',
icon: 'home|svg',
children: [ children: [
{ title: 'leaf', key: '1-1-0' }, { title: 'leaf', key: '1-1-0' },
{ title: 'leaf', key: '1-1-1' }, { title: 'leaf', key: '1-1-1' },
...@@ -29,7 +27,6 @@ export const treeData: TreeItem[] = [ ...@@ -29,7 +27,6 @@ export const treeData: TreeItem[] = [
{ {
title: 'parent 3', title: 'parent 3',
key: '2-2', key: '2-2',
icon: 'home|svg',
children: [ children: [
{ title: 'leaf', key: '2-2-0' }, { title: 'leaf', key: '2-2-0' },
{ title: 'leaf', key: '2-2-1' }, { title: 'leaf', key: '2-2-1' },
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论