组件:定义

defineExpose()

暴露组件实例属性,使父组件通过 ref 可以访问。

类型定义

ts
declare function defineExpose<T extends Record<string, any>>(exposed: T): void

参数

参数类型说明
exposedRecord<string, any>要暴露的属性和方法

示例

tsx
import { defineExpose, ref } from 'vitarx'

function Child() {
  const count = ref(0)

  defineExpose({
    count,
    increment() {
      count.value++
    }
  })

  return <div>{count}</div>
}

父组件访问:

tsx
import { useRef, onMounted } from 'vitarx'

function Parent() {
  const childRef = useRef<typeof Child>()

  onMounted(() => {
    childRef.value?.increment()
    console.log(childRef.value?.count) // 1
  })

  return <Child ref={childRef} />
}

参考组件 ref

defineValidate()

定义组件属性验证规则。

类型定义

ts
declare function defineValidate<P extends AnyProps>(
  component: Component<P>,
  validator: ValidateProps
): void

参数

参数类型说明
componentComponent<P>要验证的组件
validatorValidateProps验证函数

ValidateProps

ts
type ValidateProps = (props: AnyProps, location?: CodeLocation) => string | false | unknown

返回 string 表示验证失败的消息,返回 false 表示验证失败,其他值表示验证通过。

示例

tsx
import { defineValidate } from 'vitarx'

function MyComponent(props: { count: number }) {
  return <div>{props.count}</div>
}

defineValidate(MyComponent, (props) => {
  if (props.count < 0) {
    return 'count 不能为负数'
  }
})