指令系统
withDirectives()
为视图添加指令。
类型定义
ts
declare function withDirectives<T extends View>(
view: T,
directives: Array<[name: string | Directive, binding: DirectiveBinding]> | Array<Directive>
): T参数
| 参数 | 类型 | 说明 |
|---|---|---|
view | T 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参数
| 参数 | 类型 | 说明 |
|---|---|---|
name | string | 指令名称 |
directive | Directive | 指令对象 |
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) => voidDirectiveBinding
ts
interface DirectiveBinding {
readonly value: any
readonly arg?: string
}钩子
| 钩子 | 触发时机 |
|---|---|
created | 元素创建后 |
mounted | 元素挂载到 DOM 后 |
dispose | 元素销毁时 |
getSSRProps | SSR 时获取属性 |
示例
tsx
import { defineDirective } from 'vitarx'
const focusDirective = defineDirective('focus', {
mounted(el, binding) {
if (binding.value) {
el.focus()
}
}
})参考:自定义指令