Section 13 of 17

Vue and Nuxt

Contents

Vue maps even more directly, because Pinia setup stores look much like an NgRx Signal Store, and composables are the natural shape of a facade. Nx builds Vue and Nuxt projects with @nx/vue and @nx/nuxt.

The same workspace with a Nuxt application, and every file of this use case:

fleetline/
├── nx.json
├── package.json
├── tsconfig.base.json
├── eslint.config.mjs
├── apps/
│   └── backoffice/
│       ├── project.json
│       ├── nuxt.config.ts
│       ├── tsconfig.json
│       ├── public/
│       └── app/
│           ├── app.vue
│           ├── layouts/
│           │   ├── default.vue
│           │   └── maintenance.vue
│           ├── middleware/
│           │   └── maintenance-read.ts
│           └── pages/
│               ├── index.vue
│               └── maintenance/
│                   └── depots/
│                       └── [depotId]/
│                           └── work-orders.vue
└── libs/
    ├── maintenance/
    │   ├── feature-shell/
    │   │   └── src/
    │   │       ├── index.ts
    │   │       └── lib/
    │   │           ├── MaintenanceLayout.vue
    │   │           └── require-maintenance-read.ts
    │   ├── feature-work-orders/
    │   │   └── src/
    │   │       ├── index.ts
    │   │       └── lib/
    │   │           ├── WorkOrdersPage.vue
    │   │           └── WorkOrdersPage.spec.ts
    │   ├── ui-work-order-card/
    │   │   └── src/
    │   │       ├── index.ts
    │   │       └── lib/
    │   │           ├── WorkOrderCard.vue
    │   │           └── StatusFilter.vue
    │   ├── data-access/
    │   │   ├── project.json
    │   │   ├── tsconfig.json
    │   │   └── src/
    │   │       ├── index.ts
    │   │       └── lib/
    │   │           ├── work-orders.http.ts
    │   │           ├── work-orders.store.ts
    │   │           ├── work-orders.store.spec.ts
    │   │           ├── work-orders.providers.ts
    │   │           └── use-work-orders.ts
    │   └── model/
    │       └── src/
    │           ├── index.ts
    │           └── lib/
    │               └── work-order.ts
    ├── fleet/
    │   ├── api/
    │   │   └── src/
    │   │       └── index.ts
    │   └── data-access/
    │       └── src/
    │           └── lib/
    │               ├── vehicle-summary.store.ts
    │               └── use-vehicle-summaries.ts
    ├── identity/
    │   └── api/
    └── shared/
        ├── ui-design-system/
        ├── ui-layout/
        ├── util-http/
        └── util-date/

13.1. What maps to what

Angular Vue / Nuxt
feature component A single-file component in feature-*; the page in apps/<app>/app/pages/ only renders it
ui component A component with defineProps and defineEmits, styles in <style scoped>
shell routes File routes stay in the app; the shell library exports the layout and route middleware, and the app only re-exports them
provideWorkOrders() on a route provideWorkOrders() called in the shell layout
NgRx Store / Signal Store Pinia (setup store)
Selectors computed inside the store
Effects Async actions in the store; useAsyncData for loading during server rendering
switchMap in an effect AbortController in a store action
Facade service A composable: useWorkOrders()
@Service() with HttpClient A useWorkOrdersHttp() composable with $fetch.create and useRuntimeConfig()
provideStoreDevtools Vue DevTools with the Pinia tab

Pinia has no actions-and-reducers split. That removes the event log and the time-travel debugging of NgRx, and it also removes most of the ceremony. For the architecture it changes nothing: the store is private to data-access, and the composable is the door.

13.2. Turn off auto-imports for libraries

Nuxt imports components and composables automatically. That is convenient in a small app and fatal for boundaries: an import that is never written cannot be linted. If a feature in billing can use useWorkOrders() without an import line, the lint rule never sees the crossing.

Rules in Fleetline's Nuxt applications:

  • libraries are imported with explicit import statements through their path aliases, never registered as auto-import directories;
  • domains are not Nuxt layers, because layers auto-import their components and composables into the app;
  • the app keeps auto-imports for Vue and Nuxt APIs in its own pages/ and layouts/ only, and library code imports Nuxt functions from #imports;
  • layouts and middleware that a page refers to by name in definePageMeta are one-line re-exports from feature-shell in the app (section 13.5), because lint cannot check a name in a string.

apps/backoffice/nuxt.config.ts

export default defineNuxtConfig({
  modules: ['@pinia/nuxt'],
  components: { dirs: [] },
  imports: { scan: false },
  css: ['../../libs/shared/ui-design-system/src/styles/tokens.scss'],
  runtimeConfig: { public: { apiUrl: '' } },
});

13.3. The store

The HTTP service is a composable. It takes its configuration from the app's runtimeConfig, that is, from Nuxt's DI, just as WorkOrdersHttp in Angular takes API_BASE_URL from inject().

libs/maintenance/data-access/src/lib/work-orders.http.ts

import { useRuntimeConfig } from '#imports';
import type { WorkOrder } from '@fleetline/maintenance/model';

export function useWorkOrdersHttp() {
  const api = $fetch.create({ baseURL: useRuntimeConfig().public.apiUrl });

  return {
    list: (depotId: string, signal?: AbortSignal) => api<WorkOrder[]>(`/depots/${depotId}/work-orders`, { signal }),
    assign: (id: string, assigneeId: string) =>
      api<WorkOrder>(`/work-orders/${id}/assignee`, { method: 'PUT', body: { assigneeId } }),
  };
}

libs/maintenance/data-access/src/lib/work-orders.store.ts

import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import {
  byDueDate, emptyFilter, isOverdue, matchesFilter,
  type WorkOrder, type WorkOrderFilter,
} from '@fleetline/maintenance/model';
import { toErrorMessage } from '@fleetline/shared/util-http';
import { useWorkOrdersHttp } from './work-orders.http';

export const useWorkOrdersStore = defineStore('maintenance/work-orders', () => {
  const http = useWorkOrdersHttp();

  const byId = ref<Record<string, WorkOrder>>({});
  const filter = ref<WorkOrderFilter>({ ...emptyFilter });
  const error = ref<string | null>(null);
  let inflight: AbortController | undefined;

  const all = computed(() => Object.values(byId.value).sort(byDueDate));
  const visible = computed(() => all.value.filter((order) => matchesFilter(order, filter.value)));
  const overdueCount = computed(() => all.value.filter((order) => isOverdue(order, new Date())).length);

  async function open(depotId: string) {
    inflight?.abort();
    const controller = new AbortController();
    inflight = controller;
    filter.value = { ...emptyFilter, depotId };
    error.value = null;
    try {
      const orders = await http.list(depotId, controller.signal);
      byId.value = Object.fromEntries(orders.map((order) => [order.id, order]));
    } catch (cause) {
      if (!controller.signal.aborted) error.value = toErrorMessage(cause);
    }
  }

  function filterBy(change: Partial<Omit<WorkOrderFilter, 'depotId'>>) {
    filter.value = { ...filter.value, ...change };
  }

  async function assign(id: string, assigneeId: string) {
    const order = byId.value[id];
    if (!order) return;
    byId.value[id] = { ...order, assigneeId };
    try {
      byId.value[id] = await http.assign(id, assigneeId);
    } catch (cause) {
      byId.value[id] = order;
      error.value = toErrorMessage(cause);
    }
  }

  function $reset() {
    inflight?.abort();
    byId.value = {};
    filter.value = { ...emptyFilter };
    error.value = null;
  }

  return { byId, filter, error, visible, overdueCount, open, filterBy, assign, $reset };
});

open aborts the previous request before sending a new one: switchMap from section 9.4, written by hand. Without it, a quick depot switch would let an older response overwrite a newer one. assign aborts nothing, as with mergeMap, and on error restores the saved work order. The store catches errors and writes them to error, like the reducer in section 9.3.

byId, filter and error are returned so that Pinia serializes them into the server-rendered payload and the browser starts with the same state. inflight is not returned, so it stays private to the store instance. A setup store does not get $reset for free, so it defines its own.

13.4. The facade composable and store scope

libs/maintenance/data-access/src/lib/use-work-orders.ts

import { useAsyncData } from '#imports';
import { storeToRefs } from 'pinia';
import { toValue, type MaybeRefOrGetter } from 'vue';
import type { WorkOrder } from '@fleetline/maintenance/model';
import { useWorkOrdersStore } from './work-orders.store';

export async function useWorkOrders(depotId: MaybeRefOrGetter<string>) {
  const store = useWorkOrdersStore();
  const { visible, overdueCount, filter, error } = storeToRefs(store);

  const { pending } = await useAsyncData(
    () => `maintenance:work-orders:${toValue(depotId)}`,
    () => store.open(toValue(depotId)).then(() => true),
  );

  return {
    visible,
    overdueCount,
    filter,
    error,
    loading: pending,
    filterBy: store.filterBy,
    assign: (order: WorkOrder, assigneeId: string) => store.assign(order.id, assigneeId),
  };
}

The key is a function of depotId, so switching depots fetches again. On the server useAsyncData waits for the data; in the browser the page hydrates from the payload without a second request.

Pinia keeps one store per application, and on the server one per request. Without an extra step, maintenance state would stay in memory after leaving the domain. provideWorkOrders() gives the same scope as a route provider in Angular:

libs/maintenance/data-access/src/lib/work-orders.providers.ts

import { onUnmounted } from 'vue';
import { useWorkOrdersStore } from './work-orders.store';

export function provideWorkOrders() {
  const store = useWorkOrdersStore();
  onUnmounted(() => store.$reset());
}

onUnmounted does not run on the server, so the state reaches the payload before hydration, and in the browser it disappears when the planner leaves maintenance.

libs/maintenance/data-access/src/index.ts

export { provideWorkOrders } from './lib/work-orders.providers';
export { useWorkOrders } from './lib/use-work-orders';

A team that prefers the React-style split into server state and client state reaches for Pinia Colada, the official query layer for Pinia: the counterpart of TanStack Query, with keys, a cache and optimistic mutations. The facade and the feature do not change.

13.5. Feature, ui, shell and page

libs/maintenance/feature-work-orders/src/lib/WorkOrdersPage.vue

<script setup lang="ts">
import { useWorkOrders } from '@fleetline/maintenance/data-access';
import { StatusFilter, WorkOrderCard } from '@fleetline/maintenance/ui-work-order-card';
import { useVehicleSummaries } from '@fleetline/fleet/api';
import { EmptyState, Spinner } from '@fleetline/shared/ui-design-system';

const { depotId } = defineProps<{ depotId: string }>();

const { visible, overdueCount, filter, loading, filterBy, assign } = await useWorkOrders(() => depotId);
const vehicles = useVehicleSummaries(() => visible.value.map((order) => order.vehicleId));
</script>

<template>
  <h1>Work orders <small>{{ overdueCount }} overdue</small></h1>
  <StatusFilter
    :status="filter.status"
    :query="filter.query"
    @update:status="(status) => filterBy({ status })"
    @update:query="(query) => filterBy({ query })"
  />
  <Spinner v-if="loading" />
  <template v-else>
    <WorkOrderCard
      v-for="order in visible"
      :key="order.id"
      :work-order="order"
      :vehicle-label="vehicles[order.vehicleId]?.plate ?? ''"
      @assign="(assigneeId) => assign(order, assigneeId)"
    />
    <EmptyState v-if="visible.length === 0" title="No work orders match this filter" />
  </template>
</template>

Vue 3.5 keeps props reactive after destructuring, so () => depotId tracks route changes.

libs/maintenance/ui-work-order-card/src/lib/WorkOrderCard.vue

<script setup lang="ts">
import { computed } from 'vue';
import { isOverdue, type WorkOrder } from '@fleetline/maintenance/model';
import { Badge, MechanicPicker } from '@fleetline/shared/ui-design-system';
import { formatRelative } from '@fleetline/shared/util-date';

const { workOrder, vehicleLabel } = defineProps<{ workOrder: WorkOrder; vehicleLabel: string }>();
const emit = defineEmits<{ assign: [assigneeId: string] }>();

const overdue = computed(() => isOverdue(workOrder, new Date()));
</script>

<template>
  <article class="card" :class="{ 'card--overdue': overdue }">
    <header>
      <h3>{{ workOrder.title }}</h3>
      <Badge :tone="workOrder.priority === 'urgent' ? 'danger' : 'neutral'">{{ workOrder.priority }}</Badge>
    </header>
    <p class="vehicle">{{ vehicleLabel }}</p>
    <p class="due">{{ formatRelative(workOrder.dueAt) }}</p>
    <MechanicPicker
      :depot-id="workOrder.depotId"
      :model-value="workOrder.assigneeId"
      @update:model-value="(id) => emit('assign', id)"
    />
  </article>
</template>

<style scoped lang="scss">
.card {
  display: grid;
  gap: var(--ds-space-2);
  padding: var(--ds-space-3);
  border-radius: var(--ds-radius);
  background: var(--ds-surface);
  color: var(--ds-text);
}

.card--overdue {
  border-left: 4px solid var(--ds-danger);
}

.vehicle,
.due {
  color: var(--ds-text-muted);
}
</style>

The shell exports a layout that calls provideWorkOrders(), and a middleware with the permission check:

libs/maintenance/feature-shell/src/lib/MaintenanceLayout.vue

<script setup lang="ts">
import { provideWorkOrders } from '@fleetline/maintenance/data-access';
import { AppLayout } from '@fleetline/shared/ui-layout';

provideWorkOrders();
</script>

<template>
  <AppLayout>
    <slot />
  </AppLayout>
</template>

libs/maintenance/feature-shell/src/lib/require-maintenance-read.ts

import { abortNavigation, defineNuxtRouteMiddleware } from '#imports';
import { hasPermission } from '@fleetline/identity/api';

export const requireMaintenanceRead = defineNuxtRouteMiddleware(() => {
  if (!hasPermission('maintenance:read')) return abortNavigation({ statusCode: 403 });
});

The app only re-exports them, so lint sees the import from feature-shell:

apps/backoffice/app/layouts/maintenance.vue

<script setup lang="ts">
import { MaintenanceLayout } from '@fleetline/maintenance/feature-shell';
</script>

<template>
  <MaintenanceLayout>
    <slot />
  </MaintenanceLayout>
</template>

apps/backoffice/app/middleware/maintenance-read.ts

export { requireMaintenanceRead as default } from '@fleetline/maintenance/feature-shell';

apps/backoffice/app/pages/maintenance/depots/[depotId]/work-orders.vue

<script setup lang="ts">
import { computed } from 'vue';
import { definePageMeta, useRoute } from '#imports';
import { WorkOrdersPage } from '@fleetline/maintenance/feature-work-orders';

definePageMeta({ layout: 'maintenance', middleware: ['maintenance-read'] });

const route = useRoute();
const depotId = computed(() => String(route.params.depotId));
</script>

<template>
  <WorkOrdersPage :depot-id="depotId" />
</template>

In Vue, useVehicleSummaries from fleet/api is a small Pinia store with an ensureLoaded action, the same as in section 12.8, and a composable that calls it:

libs/fleet/data-access/src/lib/use-vehicle-summaries.ts

import { storeToRefs } from 'pinia';
import { toValue, watch, type MaybeRefOrGetter } from 'vue';
import { useVehicleSummaryStore } from './vehicle-summary.store';

export function useVehicleSummaries(ids: MaybeRefOrGetter<readonly string[]>) {
  const store = useVehicleSummaryStore();
  watch(() => toValue(ids).join(','), (key) => store.ensureLoaded(key ? key.split(',') : []), { immediate: true });
  return storeToRefs(store).entities;
}

13.6. Pitfalls specific to Nuxt

  • Linting .vue files needs vue-eslint-parser in the ESLint config, otherwise the boundary rule silently skips every component. The files pattern in section 8.2 includes **/*.vue for this reason.
  • One store per request. Pinia with @pinia/nuxt already creates one per request on the server. Never keep state in a module-level ref in a library: on the server it would be shared between users.
  • useAsyncData belongs in the facade, not in the store. The store stays usable from tests and from client-only code.
  • Top-level await in <script setup> needs <Suspense> above the component. Nuxt pages have it; a feature component rendered elsewhere has to be wrapped in one.
  • Scoped styles only. A <style> block without scoped in a library ends up in the global CSS of the whole application.