---
title: "useSigma"
description: "注入当前 SigmaGraph 的上下文，拿到原生 Sigma 与 graphology 实例。"
canonical_url: "https://sigma.mhaibaraai.cn/docs/composables/use-sigma"
---
# useSigma

> 注入当前 SigmaGraph 的上下文，拿到原生 Sigma 与 graphology 实例。

## 用法

所有其他 composable 的地基。返回的 `sigma` 与 `graph` 是**原生实例本身**——不是 Proxy，不是包装对象，sigma 与 graphology 的方法都可以直接调，库没覆盖的原生能力从这里全都拿得到。

```vue [UseSigmaExample.vue]
<script setup lang="ts">
const { data } = await useFetch('/api/small.json')
</script>

<template>
  <SigmaGraph :data="data">
    <UseSigmaPanel />
  </SigmaGraph>
</template>
```

```vue [UseSigmaPanel.vue]
<script setup lang="ts">
const { sigma, graph, isReady, whenReady } = useSigma()

async function callNative() {
  const instance = await whenReady()

  instance.getCamera().reset({ duration: 400 }) // 原生相机 API
  graph.value.setNodeAttribute('a', 'color', '#a855f7') // 原生 graphology mutation
}
</script>
```

## 示例

### 必须在子树内调用

`useSigma()` 是 `inject`，在 `SigmaGraph` 子树之外调用会抛错，错误信息里提示改用 [`useSigmaById()`](https://sigma.mhaibaraai.cn/docs/composables/use-sigma-by-id)。示例因此总是「渲染图的外壳 + 消费上下文的面板」两个文件，真实应用也是这个结构：

```vue [pages/graph.vue]
<template>
  <SigmaGraph :data="data" style="height: 70vh">
    <GraphPanel />
  </SigmaGraph>
</template>
```

### 等待实例就绪

实例在 `onMounted` 里才创建，服务端与挂载完成前 `sigma.value` 恒为 `null`；`graph` 始终存在，图数据结构不依赖 WebGL。事件回调里直接 `await whenReady()`，模板里做条件渲染用 `isReady`。

```ts
const instance = await whenReady() // 已就绪时立即兑现，多调一次没有开销
```

> [!NOTE]
> 
> 库内所有 composable 的异步方法都走了 
> 
> whenReady()
> 
> ，实例创建之前调用不会丢失，会排队等到就绪。

## API

### useSigma()

`useSigma(): SigmaContext`

在 `SigmaGraph` 子树之外调用时抛错。

#### Returns

**sigma** (`ShallowRef<Sigma | null>`): 原生 sigma 实例。SSR 期与挂载完成前为 null。

**graph** (`ShallowRef<Graph>`): 原生 graphology 实例，始终存在。

**isReady** (`Readonly<Ref<boolean>>`): 实例是否已创建。

**whenReady()** (`() => Promise<Sigma>`): 等待实例就绪，已就绪时立即兑现。

**styleOptions** (`SigmaStyleOptions`): 库内 styles 规则读取的运行时选项（dimColor / labelTier / labelTierAttribute）。由 useSigmaSelection() 与 useSigmaLabelTiers() 写入，通常不必直接使用。

**refresh()** (`(options?: { skipIndexation?: boolean }) => void`): 重新求值 styles 并重绘。纯视觉变更传 skipIndexation，改动可见性或标签时不要传。

`Sigma` 来自 `sigma`，`Graph` 来自 `graphology`，本库不 re-export 上游，需要时从原包直接 import。本库自己的类型从根出口取：

```ts
import type { SigmaContext } from '@movk/sigma'
```


## Sitemap

See the full [sitemap](https://sigma.mhaibaraai.cn/sitemap.md) for all pages.
