goview_vue/src/views/chart/hooks/useContextMenu.hook.ts

83 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-02-01 00:31:28 +08:00
import { ref, nextTick } from 'vue'
import { useChartEditStoreStore } from '@/store/modules/chartEditStore/chartEditStore'
2022-01-27 23:16:51 +08:00
import { loadingError } from '@/utils'
const chartEditStore = useChartEditStoreStore()
2022-01-27 22:30:35 +08:00
enum MenuEnum {
DELETE = 'delete'
}
2022-02-01 00:31:28 +08:00
export interface MenuOptionsItemType {
label: string
key: MenuEnum
fnHandle: Function
}
/**
* * hook
* @param menuOption
* @returns
*/
export const useContextMenu = (menuOption?: {
// 自定义右键配置
selfOptions: MenuOptionsItemType[]
// 前置处理函数
optionsHandle: Function
}) => {
const selfOptions = menuOption?.selfOptions
const optionsHandle = menuOption?.optionsHandle
2022-01-27 22:30:35 +08:00
const targetIndex = ref<number>(0)
2022-02-01 00:31:28 +08:00
// * 默认选项
const defaultOptions: MenuOptionsItemType[] = [
2022-01-27 22:30:35 +08:00
{
label: '删除',
2022-02-01 00:31:28 +08:00
key: MenuEnum.DELETE,
fnHandle: chartEditStore.removeComponentList
2022-01-27 22:30:35 +08:00
}
2022-02-01 00:31:28 +08:00
]
// * 右键选项
const menuOptions: MenuOptionsItemType[] = selfOptions || defaultOptions
2022-01-27 22:30:35 +08:00
// * 右键处理
const handleContextMenu = (e: MouseEvent, index: number) => {
e.stopPropagation()
e.preventDefault()
targetIndex.value = index
let target = e.target
while (target instanceof SVGElement) {
target = target.parentNode
}
chartEditStore.setRightMenuShow(false)
2022-01-27 22:30:35 +08:00
nextTick().then(() => {
chartEditStore.setMousePosition(e.clientX, e.clientY)
chartEditStore.setRightMenuShow(true)
2022-01-27 22:30:35 +08:00
})
}
// * 失焦
const onClickoutside = (e: MouseEvent) => {
chartEditStore.setRightMenuShow(false)
2022-01-27 22:30:35 +08:00
}
// * 事件处理
const handleMenuSelect = (key: string) => {
chartEditStore.setRightMenuShow(false)
2022-02-01 00:31:28 +08:00
const targetItem: MenuOptionsItemType[] = menuOptions.filter(
(e: MenuOptionsItemType) => e.key === key
)
if (!targetItem) loadingError()
if (targetItem.length) targetItem.pop()?.fnHandle(targetIndex.value)
2022-01-27 22:30:35 +08:00
}
2022-02-01 00:31:28 +08:00
console.log(optionsHandle ? optionsHandle(menuOptions) : menuOptions)
2022-01-27 22:30:35 +08:00
return {
2022-02-01 00:31:28 +08:00
menuOptions: optionsHandle ? optionsHandle(menuOptions) : menuOptions,
2022-01-27 22:30:35 +08:00
handleContextMenu,
onClickoutside,
handleMenuSelect,
mousePosition: chartEditStore.getMousePosition
}
}