编写带有自己 Vue 逻辑的部件,并让它连接到原语。
渲染原语 里的部件足够用,直到其中一个需要自己的逻辑。你可以只替换那个部件,并保留组合行为里的同一个 rating.ts 定义。
编写根部件
下面是生成的 RatingRoot 的替代实现。usePrimitive 创建它的实例,usePart 连接 root 槽位:
import { usePart, usePrimitive, type PartSlots } from "@ui-sdk/vue/primitive"
import { defineComponent, type HTMLAttributes } from "vue"
import { rating } from "./rating"
const RatingRoot = defineComponent(
(
props: { value?: number; defaultValue?: number } & HTMLAttributes,
{ emit }
) => {
const handle = usePrimitive(rating, () => ({
value: props.value,
defaultValue: props.defaultValue,
onValueChange(value, details) {
emit("value-change", value, details)
if (!details.canceled) {
emit("update:value", value)
}
},
}))
return usePart(handle, "root", undefined, undefined, "div")
},
{
inheritAttrs: false,
props: ["value", "defaultValue"],
emits: ["value-change", "update:value"],
slots: Object as PartSlots<typeof rating, "root">,
}
)
export { RatingRoot }在 setup 里调用这两个辅助函数。选项 getter 让值保持最新;usePrimitive 还会与子部件共享实例。usePart 返回一个渲染函数,转发 attrs 和槽位。inheritAttrs: false 避免 attrs 被应用两次。用 defineComponent 定义部件,即使在 Vapor 应用里也是如此:<script setup vapor> 组件无法调用这两个辅助函数。
HTMLAttributes 让 TypeScript 调用方可以使用原生 attrs;只有 value 和 defaultValue 声明为组件 props,所以其他 attrs 仍然会到达 usePart。
这个根在变更回调有机会取消之后发出 update:value,以此支持 v-model:value。PartSlots 为默认槽位和 #render 槽位提供类型。适配器管理实例的生命周期。
连接子部件
把原语本身传给 usePart,它会找到上方根共享的实例。这个 RatingStar 既能用在上面手写的根里,也能用在生成的 RatingRoot 里:
import { usePart, type PartSlots } from "@ui-sdk/vue/primitive"
import { defineComponent, type ButtonHTMLAttributes } from "vue"
import { rating } from "./rating"
const RatingStar = defineComponent(
(props: { value: string } & Omit<ButtonHTMLAttributes, "value">) => {
return usePart(
rating,
"star",
() => ({ value: props.value }),
undefined,
"button"
)
},
{
inheritAttrs: false,
props: ["value"],
slots: Object as PartSlots<typeof rating, "star">,
}
)
export { RatingStar }在渲染评分里用它替换生成的星。ButtonHTMLAttributes 为它的原生 attrs 提供类型。value getter 标识这颗星;其余的 props 传给它的按钮。把它放在 RatingRoot 里,并给它一个 aria-label。
合并 props
usePart 把组件的 attrs 与槽位的 attrs 合并。槽位的属性优先,类和样式会合并,你的监听器先运行。你传入的 id,或者名称或输入提示,比如 aria-label 或 autocomplete,会替换槽位的值。在监听器里调用 preventDefault() 可以跳过内置处理函数。
最后一个参数可以是一个标签名,或者一个带有 tag、children 和 extend 的对象。用 extend 在槽位的 props 之后追加额外 props,比如 Field 提供的属性。保持槽位的角色、ID 和 ARIA 状态不变。
组合浮层
自定义组件也可以使用现有的 Popover 或 Dialog。组合现有的浮层用一个 emoji 选择器展示了这种连接。