<Primitive>

Gitlab
Compose functionality onto alternative element types or your own Vue components.
Added since: v0.3.0
Last changed:

When you are building a component, in some cases you might want to allow user to compose some functionalities onto the underlying element, or alternative element. This is where Primitive comes in handy as it expose this capability to the user.

Usage

Changing as value

If you want to change the default element or component being render, you can set the default as when defining the props.

app/components/MyButton.vue
<script setup lang="ts">
import type { 
PrimitiveProps
} from '@nobears-front-end/utils'
import {
Primitive
} from '@nobears-front-end/utils'
const {
as
= 'span', ...
props
} =
defineProps
<
PrimitiveProps
>();
</script> <template> <!-- Now this element will be rendered as `span` by default --> <
Primitive
v-bind="
props
"
:
as
="
as
">
... </Primitive> </template>

Render asChild

Change the default rendered element for the one passed as a child, merging their props and behavior.

app/components/MyButton.vue
<script setup lang="ts">
import type { 
PrimitiveProps
} from '@nobears-front-end/utils'
import {
Primitive
} from '@nobears-front-end/utils'
const
props
=
defineProps
<
PrimitiveProps
>();
</script> <template> <
Primitive
v-bind="
props
"
as-child
>
<!-- Passes the props and behavior to the child element --> <
button
>
Click me </
button
>
</Primitive> </template>

API Reference

Props

as
string | Component
The element or component that should be rendered. Prioritizes components over elements when both share the same name.

Will be overwritten with "template" when asChild is enabled.
asChild
boolean
Change the default rendered element for the one passed as a child, merging their props and behavior.

Changelog

v0.3.1

on

#72aad29e

-

improvement: the Primitive component is now used from reka-ui