Skip to content

component

组件工具函数。

导入

typescript
import { useExpose, useEmit, useMethod, useMount, useMounted, useActivated } from '@cloudcome/utils-vue/component'

类型定义

HookListener

typescript
type HookListener = () => MaybePromise<unknown>

HookListenerWithDispose

typescript
type HookListenerWithDispose = () => MaybePromise<undefined | HookListener>

函数

useExpose

暴露组件实例方法。

typescript
function useExpose<T>(Comp: T): Ref<ComponentExposed<T> | null>

参数

参数类型描述
CompT组件实例引用

返回值

Ref<ComponentExposed<T> | null> - 组件实例引用

示例

typescript
// 子组件
const childRef = ref()

// 父组件
const child = useExpose(childRef)

// 调用子组件方法
child.value?.someMethod()

useEmit

监听组件事件。

typescript
function useEmit<T, E extends PickEmits<Required<ComponentProps<T>>>, K extends keyof E>(
  Comp: T,
  event: K,
  listener: E[K]
): E[K]

参数

参数类型描述
CompT组件实例引用
eventK事件名称
listenerE[K]事件监听函数

返回值

E[K] - 传入的监听函数

示例

typescript
const childRef = ref()

useEmit(childRef, 'update', (value: string) => {
  console.log('收到更新事件:', value)
})

useMethod

调用组件方法。

typescript
function useMethod<T, M extends PickMethods<Required<ComponentProps<T>>>, K extends keyof M>(
  Comp: T,
  name: K,
  method: M[K]
): M[K]

参数

参数类型描述
CompT组件实例引用
nameK方法名称
methodM[K]方法实现

返回值

M[K] - 传入的方法

示例

typescript
const childRef = ref()

useMethod(childRef, 'validate', () => {
  // 验证逻辑
  return true
})

useMount

在组件挂载前执行。

typescript
function useMount(beforeMount: HookListenerWithDispose): void

参数

参数类型描述
beforeMountHookListenerWithDispose挂载前回调,可返回清理函数

示例

typescript
useMount(() => {
  console.log('组件即将挂载')
  
  // 返回清理函数
  return () => {
    console.log('组件即将卸载')
  }
})

useMounted

在组件挂载后执行。

typescript
function useMounted(mounted: HookListenerWithDispose): void

参数

参数类型描述
mountedHookListenerWithDispose挂载后回调,可返回清理函数

示例

typescript
useMounted(() => {
  console.log('组件已挂载')
  
  // 返回清理函数
  return () => {
    console.log('组件即将卸载')
  }
})

useActivated

在组件激活时执行(keep-alive)。

typescript
function useActivated(activated: HookListenerWithDispose): void

参数

参数类型描述
activatedHookListenerWithDispose激活时回调,可返回清理函数

示例

typescript
useActivated(() => {
  console.log('组件已激活')
  
  // 返回清理函数
  return () => {
    console.log('组件即将停用')
  }
})

基于 MIT 许可发布