# Vue: state and slots

Use this pattern when your Vue editor needs app-owned specs, a sibling inspector, and custom node content that updates independently of the canvas. Defaults seed the live model once; controlled refs provide a return path from that model into your app.

Start from the project in the [Vue quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start). Its packages and entry file stay in place. Add the components below, then import and render the component you want to try inside the existing `src/App.vue` template; keep the starter's other imports, styles, and entry wiring.

## 1. Choose controlled refs or mount-time defaults

Build on the [Vue quick start's controlled bindings](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start#2-use-app-owned-state-and-a-custom-node-slot) for [`GrafloriaFlow`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#grafloriaflow), [`NodeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-nodespec), and [`EdgeSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-edgespec): here, slot actions return engine-driven removals to your refs.

This component renders Build connected to Deploy. Its custom cards share a provider with an inspector. Removing a card through its engine updates the controlled node ref as well as the diagram.

```vue title="src/components/StateFlow.vue"
<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef } from 'vue';
import { GrafloriaFlow, GrafloriaProvider, GrafloriaCommentPanel } from '@grafloria/vue';
import type { DiagramInstance, NodeSpec, EdgeSpec } from '@grafloria/renderer';
import type { CommentStore } from '@grafloria/engine';
import FlowInspector from './FlowInspector';
import MetricCard from './MetricCard.vue';

const nodes = ref<NodeSpec[]>([
  {
    id: 'build', type: 'card',
    position: { x: 60, y: 90 }, size: { width: 230, height: 140 },
    data: { title: 'Build', owner: 'CI' },
    ports: [{ id: 'build-out', side: 'right', type: 'output', dataType: 'number' }],
  },
  {
    id: 'deploy', type: 'card',
    position: { x: 420, y: 90 }, size: { width: 230, height: 140 },
    data: { title: 'Deploy', owner: 'CD' },
    ports: [{ id: 'deploy-in', side: 'left', type: 'input', dataType: 'number' }],
  },
]);
const edges = ref<EdgeSpec[]>([
  { id: 'pipeline', source: 'build', target: 'deploy',
    sourceHandle: 'build-out', targetHandle: 'deploy-in' },
]);
const comments = shallowRef<CommentStore | null>(null);

onBeforeUnmount(() => comments.value?.dispose());

function onInit(instance: DiagramInstance): void {
  const store = instance.getCommentStore();
  if (store) {
    store.createThread({ kind: 'node', id: 'build' }, 'Review the build before deploying.');
    comments.value = store;
  }
}
</script>

<template>
  <GrafloriaProvider>
    <FlowInspector :standalone="false" />
    <div style="height: 400px; width: 100%">
      <GrafloriaFlow
        v-model:nodes="nodes"
        v-model:edges="edges"
        :comments="true"
        :interaction="{ portVisibility: 'always' }"
        @init="onInit"
      >
        <template #node-card="{ node, data, engine }">
          <div class="card">
            <strong>{{ data['title'] }}</strong>
            <div>Owner: {{ data['owner'] }}</div>
            <MetricCard :metric-id="node.id" />
            <button type="button" @pointerdown.stop @click.stop="engine.removeNode(node.id)">
              Remove {{ data['title'] }}
            </button>
          </div>
        </template>
      </GrafloriaFlow>
    </div>
    <GrafloriaCommentPanel v-if="comments" :store="comments" />
  </GrafloriaProvider>
</template>

<style scoped>
.card {
  height: 100%;
  box-sizing: border-box;
  padding: 12px;
  background: white;
  color: #243047;
  border: 1px solid #94a5f0;
  border-radius: 10px;
}
</style>
```

Complete the inspector and metric files in the next two steps before running this component. [`DiagramInstance`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-renderer-instance-diagraminstance) arrives through `@init`. Enabling `comments` creates a [`CommentStore`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-comments#commentstore); `getCommentStore()` returns it, or `null` when comments are disabled. [`GrafloriaCommentPanel`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#grafloriacommentpanel) displays the same store, including the review thread anchored to Build. The flow owns teardown of its instance. Dispose the comment store in the containing component's `onBeforeUnmount` hook to remove its subscriptions.

Build and Deploy appear as connected cards with owners, run counts, increment and remove buttons, a sibling selection readout, and the review comment.

For an editor where the diagram owns all subsequent changes, use the uncontrolled form from the [Vue quick start's first flow](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start#1-create-a-vue-project-and-mount-the-first-flow).

Vue's `update:nodes` requires a bound `nodes` prop and reports additions, removals, and committed node gestures rather than every drag frame, with selection on a separate event surface; see the [Qwik quick start's ownership pattern](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/qwik-quick-start#2-mount-the-flow-and-return-changes-to-signals) for the shared distinction between controlled inputs and mount-time `defaultNodes` and `defaultEdges`.

## 2. Expose the instance to a sibling inspector

[`GrafloriaProvider`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#grafloriaprovider) publishes the flow's instance to siblings beneath it. Call the composables in the inspector's setup, not in the component that renders the provider: injection looks upward through ancestors.

Unlike the values used in the [React sibling-panel pattern](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/react-state-and-content#2-share-the-instance-with-sibling-panels), Vue's [`useGrafloria`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#usegrafloria), [`useSelection`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#useselection), and [`useViewport`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#useviewport) return refs read through `.value`, while [`useOnSelectionChange`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#useonselectionchange) registers its callback in setup with scope-owned teardown.

The inspector module includes a sized flow for standalone use. Pass `:standalone="false"`, as in `StateFlow.vue`, to show only the panel beside an existing flow.

```ts title="src/components/FlowInspector.ts"
import { defineComponent, h, ref } from 'vue';
import { GrafloriaFlow, GrafloriaProvider, useGrafloria, useSelection, useViewport, useOnSelectionChange } from '@grafloria/vue';
import type { NodeSpec, EdgeSpec } from '@grafloria/renderer';

const InspectorPanel = defineComponent({
  setup() {
    const instance = useGrafloria();
    const selection = useSelection();
    const viewport = useViewport();
    const lastSelection = ref('No selection event yet');

    useOnSelectionChange((change) => {
      lastSelection.value = change.nodes.map((node) => node.id).join(', ') || 'No nodes selected';
    });

    function zoomIn(): void {
      const api = instance.value;
      if (api) api.viewport.setZoom(viewport.value.zoom * 1.2);
    }

    return () => h('aside', [
      h('button', { type: 'button', disabled: !instance.value, onClick: zoomIn }, 'Zoom in'),
      h('p', `${selection.value.nodes.length} nodes and ${selection.value.edges.length} edges selected · ` +
        `zoom ${viewport.value.zoom.toFixed(2)} · ` +
        `camera ${viewport.value.x.toFixed(0)}, ${viewport.value.y.toFixed(0)}`),
      h('p', `Last selection event: ${lastSelection.value}`),
    ]);
  },
});

export default defineComponent({
  props: { standalone: { type: Boolean, default: true } },
  setup(props) {
    const nodes: NodeSpec[] = [
      { id: 'build', label: 'Build', position: { x: 60, y: 90 }, size: { width: 180, height: 70 } },
      { id: 'deploy', label: 'Deploy', position: { x: 380, y: 90 }, size: { width: 180, height: 70 } },
    ];
    const edges: EdgeSpec[] = [{ id: 'pipeline', source: 'build', target: 'deploy' }];
    return () => props.standalone
      ? h(GrafloriaProvider, null, {
          default: () => [
            h(InspectorPanel),
            h('div', { style: 'height:400px;width:100%' }, [
              h(GrafloriaFlow, { defaultNodes: nodes, defaultEdges: edges }),
            ]),
          ],
        })
      : h(InspectorPanel);
  },
});
```

To run this step independently, add this host and import it into the existing `src/App.vue` script. Render the imported component inside the existing template; `FlowInspector` already includes the mounted flow, so this host adds no specs or canvas wiring from the [Vue quick start](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/vue-quick-start#1-create-a-vue-project-and-mount-the-first-flow):

```vue title="src/components/InspectorFlow.vue"
<script setup lang="ts">
import FlowInspector from './FlowInspector';
</script>

<template>
  <FlowInspector />
</template>
```

A Zoom in button and selection and camera readouts appear above Build connected to Deploy.

Click a node to select it: the counts and last-event text change from the library's selection events. Click Zoom in: the camera readout follows the applied zoom, including its limits. For consumers in the flow's default slot or inside a custom node, the flow provides its own instance context even without an outer provider.

## 3. Keep custom slot content reactive

An exact `#node-card` slot opts nodes of type `card` into HTML rendering. The engine positions the box and keeps its connections; your slot paints the interior. The slot receives `node`, the live model; `data`, its payload or an empty object; and `engine`, the same engine returned by `getEngine()`.

For content driven by your app, render a component that reads a reactive source by node id. The following store and component give each card a live run count. Clicking Increment runs updates that card without changing diagram membership or requesting a canvas repaint.

```ts title="src/components/metrics.ts"
import { reactive } from 'vue';

export const runs = reactive(new Map<string, number>([
  ['build', 3],
  ['deploy', 1],
]));
```

```vue title="src/components/MetricCard.vue"
<script setup lang="ts">
import { computed } from 'vue';
import { runs } from './metrics';

const props = defineProps<{ metricId: string }>();
const count = computed(() => runs.get(props.metricId) ?? 0);

function increment(): void {
  runs.set(props.metricId, count.value + 1);
}
</script>

<template>
  <div>
    Runs: {{ count }}
    <button type="button" @pointerdown.stop @click.stop="increment">Increment runs</button>
  </div>
</template>
```

The card root in `StateFlow.vue` fills its host with `height: 100%` and includes padding inside its declared footprint with `box-sizing: border-box`. The footprint itself comes from the node's `size`. Ports also belong to the spec: the sample replaces the default ports with a numeric output and input and pins the edge to their ids. Try the [slot-defined custom nodes demo](https://grafloria.com/demos-vue/#/nodes/html-nodes) and the [typed ports demo](https://grafloria.com/demos-vue/#/ports/typed-ports). If you only need a styled shape rather than Vue content, compare the [shape-based nodes demo](https://grafloria.com/demos-vue/#/nodes/custom-nodes).

| Slot choice | What renders |
| --- | --- |
| `#node-<type>` | An exact type match opts a plain spec into custom rendering when `custom` is omitted. |
| `#node` | A wildcard paints already-custom nodes without an exact slot; set `custom: true` to opt such a spec in. |
| Explicit `custom: true` | The node uses the custom path, with an exact slot preferred over the wildcard. |
| Explicit `custom: false` | The node stays on the SVG path, even with a matching slot. |

The Remove button uses `engine.removeNode(node.id)`, so deletion goes through command history rather than mutating your Vue array. Undo and redo belong to the engine, not the instance. See [Commands and history](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/commands-and-history) for event-driven history controls, or try the [Vue undo/redo demo](https://grafloria.com/demos-vue/#/interaction/undo-redo).

## 4. Take snapshots, request layout, and reopen a saved document

The flow's template-ref surface exposes `getInstance()`, `applyLayout()`, and `snapshot()`. `snapshot()` returns the model's schema-versioned serialization, or `null` before initialization. `applyLayout()` accepts a registry name or `{ name, options }` and emits `layoutDone` after the layout resolves. For typed application code, capture the instance through `@init` and use its model for a snapshot; use the component's `layout` prop for declarative layout.

This separate example starts with two plain boxes. Arrange top to bottom changes the layout request. Save document captures the live model in an integrity-checked envelope. Open saved copy loads that string once and renders a separate mounted view, leaving newer edits in the original untouched.

[`DiagramSerializer`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-engine-serialization#diagramserializer) writes the envelope. [`fromDocument`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-core#fromdocument) checks and loads it into a render spec; [`GrafloriaDiagram`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#grafloriadiagram) mounts that spec rather than hand-projecting models into node arrays.

```vue title="src/components/SnapshotFlow.vue"
<script setup lang="ts">
import { ref, shallowRef } from 'vue';
import { GrafloriaFlow, GrafloriaDiagram } from '@grafloria/vue';
import { fromDocument } from '@grafloria/element';
import { DiagramSerializer } from '@grafloria/engine';
import type { DiagramInstance, NodeSpec, EdgeSpec } from '@grafloria/renderer';

const instance = shallowRef<DiagramInstance | null>(null);
const copy = shallowRef<ReturnType<typeof fromDocument> | null>(null);
const saved = ref('');
const snapshotText = ref('');
const status = ref('No saved document');
const layout = ref({ name: 'dagre', options: { direction: 'LR' } });
const nodes: NodeSpec[] = [
  { id: 'build', label: 'Build', position: { x: 60, y: 90 }, size: { width: 180, height: 70 } },
  { id: 'deploy', label: 'Deploy', position: { x: 380, y: 90 }, size: { width: 180, height: 70 } },
];
const edges: EdgeSpec[] = [{ id: 'pipeline', source: 'build', target: 'deploy' }];

function onInit(api: DiagramInstance): void {
  instance.value = api;
}

function snapshot(): void {
  const api = instance.value;
  if (api) snapshotText.value = JSON.stringify(api.getModel().serialize(), null, 2);
}

function save(): void {
  const api = instance.value;
  if (!api) return;
  saved.value = JSON.stringify(new DiagramSerializer().serializeEnvelope(api.getModel()));
  status.value = 'Saved the current document';
}

function openCopy(): void {
  try {
    const loaded = fromDocument(saved.value);
    copy.value = loaded;
    status.value = 'Opened a saved copy; the original is unchanged';
  } catch (error) {
    status.value = error instanceof Error ? error.message : 'Cannot load the document';
  }
}
</script>

<template>
  <section>
    <button type="button" @click="layout = { name: 'dagre', options: { direction: 'TB' } }">
      Arrange top to bottom
    </button>
    <button type="button" :disabled="!instance" @click="snapshot">Inspect snapshot</button>
    <button type="button" :disabled="!instance" @click="save">Save document</button>
    <button type="button" :disabled="!saved" @click="openCopy">Open saved copy</button>
    <p>{{ status }}</p>
    <div style="height: 400px; width: 100%">
      <GrafloriaFlow :default-nodes="nodes" :default-edges="edges" :layout="layout" @init="onInit" />
    </div>
    <pre v-if="snapshotText">{{ snapshotText }}</pre>
    <label>
      Saved document
      <textarea v-model="saved" rows="4" style="width: 100%" />
    </label>
    <template v-if="copy">
      <h3>Saved copy</h3>
      <div style="height: 400px; width: 100%">
        <GrafloriaDiagram :spec="copy" />
      </div>
    </template>
  </section>
</template>
```

![Build connects to Deploy beneath the layout, snapshot, save, and open-copy buttons; the Saved document field starts empty.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/28cd59d3e49b915d0320f2cb6319bc39.png)

The snapshot includes nodes, links, ports, groups, metadata, the model viewport, and any comments or ink. The mounted copy retains nodes and links with their ports and node metadata, groups, and ink, but starts with a fresh camera position and zoom and does not retain diagram-level metadata or comments. The saved model viewport is not the live camera state. The snapshot does not contain your Vue component code, the `runs` map, or the engine's command history. Persist app-owned metric state separately. This example uses built-in boxes in both views; restoring custom content also requires the app's painter. For persistence and custom rendering on reload, continue with [Save and restore documents](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/save-and-restore).

To see a failed integrity check, save, change a node label inside the Saved document field without changing the checksum, then open it. The loader throws a checksum error, the status displays it, and the existing copy remains mounted. A truncated JSON string also fails instead of replacing the view.

Other template-ref conveniences are `exportSvg()` (a synchronous result containing SVG and warnings), `exportPdf()` (a vector PDF result), `exportDiagram()` (the instance's asynchronous image export), `exportText()` and `loadText()` (Mermaid-compatible text out and back), and `fitView()` (frame content on request). See [Export images and vector PDF](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/export-diagram) and [Import Mermaid and draw.io](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/import-diagram-text) for those tasks. Compare the [save-and-restore demo](https://grafloria.com/demos-vue/#/interaction/save-and-restore) and [controlled Mermaid viewer](https://grafloria.com/demos-vue/#/misc/mermaid-viewer).

## 5. Use dashboard state through its component

[`GrafloriaDashboard`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-vue#grafloriadashboard) uses the same Vue idiom for dashboard views: `v-model:active-view` selects the visible view, and `#widget-<kind>` customizes a widget's interior. Kinds without a slot use the shipped painters. This component renders a built-in Build runs KPI; the selector switches to Deploy runs.

```vue title="src/components/PipelineDashboard.vue"
<script setup lang="ts">
import { ref } from 'vue';
import { GrafloriaDashboard } from '@grafloria/vue';
import type { DashboardViewSpec } from '@grafloria/element';

const activeView = ref('build-view');
const views: DashboardViewSpec[] = [
  { id: 'build-view', widgets: [
    { id: 'build-kpi', kind: 'kpi', span: 3, rows: 1, data: { label: 'Build runs', value: 3 } },
  ] },
  { id: 'deploy-view', widgets: [
    { id: 'deploy-kpi', kind: 'kpi', span: 3, rows: 1, data: { label: 'Deploy runs', value: 1 } },
  ] },
];
</script>

<template>
  <label>
    View
    <select v-model="activeView">
      <option value="build-view">Build</option>
      <option value="deploy-view">Deploy</option>
    </select>
  </label>
  <div style="height: 400px; width: 100%">
    <GrafloriaDashboard :views="views" v-model:active-view="activeView" />
  </div>
</template>
```

![The view selector shows Build, and the Build runs KPI displays 3.](https://atloriaassets.blob.core.windows.net/assets/a438221c-c1af-407c-b9e6-a56c986db846/5a223f39657e6bb1ca12c0b93bf62fe7.png)

[`DashboardViewSpec`](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/grafloria-element-dashboard-kit-interfaces#dashboardviewspec) describes the initial views. The dashboard's `ready` event supplies its handle; its template ref exposes `getHandle()` and `snapshot()`. Use `layoutChange` for committed widget-layout changes rather than assuming the initial `views` array reflects gestures. Continue with [Build a dashboard](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/build-dashboard) for widget slots and board persistence.

## Options that matter

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `nodes`, `edges` | `NodeSpec[]`, `EdgeSpec[]` | `undefined` | Controlled inputs; pair them with their `v-model` return paths. |
| `defaultNodes`, `defaultEdges` | `NodeSpec[]`, `EdgeSpec[]` | `undefined` | Seed an uncontrolled flow at mount. |
| `layout` | Registry name or `{ name, options }` | `undefined` | Request layout at mount and when its value changes. |
| `comments` | `boolean` or shared store object | `undefined` | `true` creates a comment store; an object shares one. |
| Dashboard `activeView` | `string` | `undefined` | Select a view through `v-model:active-view`. |
| Dashboard `layout` | `'grid'` or `'split'` | `undefined` | Override the board layout and switch it live: cell grid or splitter tree. |
| Dashboard `sizing` | `'fit'` or `'grow'` | `undefined` | Override sizing: fit the board or allow it to grow. |
| Dashboard `static` | `boolean` | `undefined` | Enable the viewer mode without drag or resize handles. |

## Pitfalls and related tasks

- Treat controlled specs as a projection, not the persistence format. [Save and restore documents](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/save-and-restore) covers the fidelity boundary.
- Existing ids preserve live models during reconciliation. For externally replaced data, follow [Edit nodes from your UI](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/edit-nodes).
- Request a new layout intentionally after data changes; see [Lay out a diagram](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/lay-out-diagram).
- For live model-derived content, see [Compute connected data](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/compute-connected-data). App-owned reactive content uses the component pattern above.
- For resolved canvas dimensions inside nested layouts, see [Nest containers and lanes](https://bench-grafloria-61d.atloria.app/p/bench-grafloria-61d-mQCmWpDrxv/developer/nest-containers).
