跳至正文

导入与类型 ​

每个组件组都公开独立的 ESM 子路径。组件页列出该入口导出的组件、函数、常量和类型。导入路径可直接用于 Vite、支持 ESM 的构建工具以及 Node SSR。

组件命名空间 ​

组件使用 S 前缀。文档示例在脚本中导入 SInput,在模板中使用 <s-input>。复合名称遵循同一规则,例如 SDialogContent 对应 <s-dialog-content>,SInputOtp 对应 <s-input-otp>。

vue
<template>
  <s-input v-model="email" type="email" aria-label="工作邮箱" />
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { SInput } from '@icecreamqaq/shadcn/input'

const email = ref('')
</script>
vue
<template>
  <s-input v-model="email" type="email" aria-label="工作邮箱" />
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { SInput } from '@icecreamqaq/shadcn/input'

export default defineComponent({
  components: { SInput },
  data() {
    return { email: '' }
  },
})
</script>

全局注册 ​

在应用入口安装一次插件,各页面即可直接使用带前缀的组件。使用 /plugin 入口也会为 Vue 模板加载全局组件类型和自动补全。

ts
import { createApp } from 'vue'
import ShadcnVue from '@icecreamqaq/shadcn/plugin'
import '@icecreamqaq/shadcn/style.css'
import App from './App.vue'

createApp(App).use(ShadcnVue).mount('#app')

包根入口的默认导出也是同一个插件。按需使用时直接导入具体组件即可。原有 Input、Button 等命名导出仍可使用,函数和类型沿用 toast、ButtonVariants 等名称。库内 Vue 组件的运行时名称也使用前缀,例如按名称缓存输入框时可写 <keep-alive include="SInput">。

两种导入方式 ​

ts
import { SButton, type ButtonVariants } from '@icecreamqaq/shadcn/button'
import { SDialog, SDialogContent, SDialogTitle } from '@icecreamqaq/shadcn'

const variant: ButtonVariants['variant'] = 'outline'

子路径适合明确依赖范围。多个组件也可以统一从根入口导入。两处导出指向同一组件,应用引入一份 CSS 即可。

响应式值与插槽 ​

按每个组件页的签名选择 v-model。例如 SSwitch 更新布尔值,SDialog 通过 v-model:open 更新打开状态。部分组件通过插槽直接提供内部状态。

vue
<template>
  <s-switch v-model="enabled" aria-label="邮件通知" />
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { SSwitch } from '@icecreamqaq/shadcn/switch'

const enabled = ref(true)
</script>
vue
<template>
  <s-switch v-model="enabled" aria-label="邮件通知" />
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { SSwitch } from '@icecreamqaq/shadcn/switch'

export default defineComponent({
  components: { SSwitch },
  data() {
    return { enabled: true }
  },
})
</script>

在 as-child 触发器中放置单个可交互元素,属性、事件和键盘焦点就会传递到该元素。完整示例见对话框和下拉菜单。

通知入口 ​

方案挂载组件触发通知
Sonner从 @icecreamqaq/shadcn/sonner 导入 SToaster同一入口的 toast.success('保存成功')
旧版 SToast从 @icecreamqaq/shadcn/toast 导入 SToastToaster同一入口的 useToast().toast({ title: '保存成功' })

在根入口,SToaster 和 toast 对应 Sonner,SToastToaster 和 legacyToast 对应旧版。请将每套通知的调用函数与相应挂载组件搭配。

服务端渲染 ​

在 SSR 入口导入 ESM 组件,客户端应用入口负责加载 CSS。以下示例可在安装组件包和 Vue 的 Node 项目内运行。

js
import { createSSRApp, h } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { SButton } from '@icecreamqaq/shadcn/button'

const app = createSSRApp(() => h(SButton, { variant: 'outline' }, () => '保存'))
const html = await renderToString(app)