---
title: "@xid-kit/vue"
description: "基于 @xid-kit/core 的 Vue 3 插件、composable 和无样式组件。"
locale: "zh-Hans"
---

> Documentation Index
> Fetch the locale documentation index at: https://xid.dev/zh-hans/llms.txt
> Use this file to discover all available pages before exploring further.

# @xid-kit/vue

## 状态

包状态为 **当前包**。Vue 3 插件、composable 和无样式组件已实现。在真实生产基础设施上的 IdP 往返验证仍待人工核实。

## 插件配置

在 `main.ts` 中注册一次 `XidPlugin`。它创建 `XidClient` 单例，通过 `XID_INJECTION_KEY` 提供，并调用 `client.load()` 来补水会话状态。

```ts
// main.ts
import { createApp } from 'vue'
import { XidPlugin } from '@xid-kit/vue'
import App from './App.vue'

const app = createApp(App)
app.use(XidPlugin, { apiUrl: 'https://your-tenant.xid.dev' })
app.mount('#app')
```

## 组合式函数

```ts
import { useAuth, useUser, useOrganization, useSession } from '@xid-kit/vue'

const auth = useAuth()
// auth.isLoaded / auth.isSignedIn / auth.userId
// auth.getToken()  -> Promise<Result<string, XidError>>
// auth.signOut()   -> Promise<Result<null, XidError>>

const userRef = useUser()
// userRef.value.isLoaded && userRef.value.isSignedIn -> userRef.value.user.id

const orgRef = useOrganization()
// orgRef.value.organization / orgRef.value.membership / orgRef.value.setActive()

const sessionRef = useSession()
// sessionRef.value.session / sessionRef.value.getToken()
```

## 组件

```vue
<template>
  <SignInButton sign-in-url="/sign-in" redirect-url="/dashboard">Log in</SignInButton>
  <SignOutButton redirect-url="/">Log out</SignOutButton>

  <Protect role="org:admin">
<AdminPanel />
<template #fallback><p>Access denied.</p></template>
  </Protect>

  <Protect permission="org:member:read">
<MemberList />
  </Protect>
</template>

<script setup lang="ts">
import { SignInButton, SignOutButton, Protect } from '@xid-kit/vue'
</script>
```

## 导出的 API

| 导出 | 类型 | 用途 |
| --- | --- | --- |
| `XidPlugin` | Vue 插件 | app.use 入口点；注册 XidClient 并调用 client.load() |
| `createXidClient` | function | 返回独立 XidClient 实例的工厂 |
| `useXidClient` | 组合式函数 | 返回注入的 XidClient；插件未注册时抛出异常 |
| `XID_INJECTION_KEY` | InjectionKey | 用于 provide 和 inject XidClient 单例的 Symbol |
| `useXid` | 组合式函数 | 完整状态 ref 及所有客户端操作（UseXidReturn） |
| `useAuth` | 组合式函数 | isLoaded、isSignedIn、userId、getToken、signOut |
| `useUser` | 组合式函数 | 封装 isLoaded / isSignedIn / user 判别联合的 ref |
| `useOrganization` | 组合式函数 | 活跃组织、成员关系及 setActive 操作 |
| `useSession` | 组合式函数 | 活跃会话及 getToken 操作 |
| `SignInButton` | 组件 | 点击时重定向到登录 URL 的无样式按钮 |
| `SignOutButton` | 组件 | 点击时调用 client.signOut() 的无样式按钮 |
| `Protect` | 组件 | 基于 slot 的角色与权限门控，支持默认 slot 和回退 slot |

Source: https://xid.dev/zh-hans/sdks/vue/index.mdx
