指令系统

withDirectives()

为视图添加指令。

类型定义

ts
declare function withDirectives<T extends View>(
  view: T,
  directives: Array<[name: string | Directive, binding: DirectiveBinding]> | Array<Directive>
): T

参数

参数类型说明
viewT extends View目标视图
directives[name | Directive, binding][] | Directive[]指令数组

返回值

类型说明
T添加了指令的视图

示例

tsx
import { withDirectives, h } from 'vitarx'
import { focusDirective } from './directives'

const view = withDirectives(h('input'), [[focusDirective, true]])

defineDirective()

定义自定义指令。

类型定义

ts
declare function defineDirective(name: string, directive: Directive): void

参数

参数类型说明
namestring指令名称
directiveDirective指令对象

Directive 接口

ts
interface Directive {
  name?: string
  created?: DirectiveHook
  mounted?: DirectiveHook
  dispose?: DirectiveHook
  getSSRProps?(binding: DirectiveBinding, view: ElementView): Record<string, any> | void
}

type DirectiveHook = (el: HostElement, binding: DirectiveBinding, view: ElementView) => void

DirectiveBinding

ts
interface DirectiveBinding {
  readonly value: any
  readonly arg?: string
}

钩子

钩子触发时机
created元素创建后
mounted元素挂载到 DOM 后
dispose元素销毁时
getSSRPropsSSR 时获取属性

示例

tsx
import { defineDirective } from 'vitarx'

const focusDirective = defineDirective('focus', {
  mounted(el, binding) {
    if (binding.value) {
      el.focus()
    }
  }
})

参考自定义指令