State and props
Vue follows the same ownership rules as State without globals, mapped onto three distinct component scopes: <script setup> belongs to a single instance, plain <script> and composable top-levels are shared across instances, and props are borrowed from the parent.
In short
- Instance state:
refandletinside<script setup>are scoped per instance—nono-mutable-global. - Shared state: move module-level composable state into a factory or a Pinia setup store.
- Borrowed props: read props without mutating them; use
defineModel()ordefineEmits()to request updates. - TSX /
defineComponent: type props cleanly without casts.
<script setup> runs once per instance
Vue runs <script setup> for every instance of the component, like the body of a function. A let or a ref there belongs to that one instance, so no-mutable-global doesn't apply:
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { ref } from "vue";
let added = 0;
const todos = ref<string[]>([]);
function add(title: string): void {
added += 1;
todos.value.push(`${added}. ${title}`);
}
</script>
<template>
<button @click="add('Write the docs')">Add</button>
<p>{{ todos.length }} to do</p>
</template>Functions declared in <script setup> are still followed like any other: a failure one of them can propagate is tracked into the functions that call it, and into the template.
<script> and composable files are shared
A plain <script> block runs once, when the module loads, and every instance shares it. The same goes for the top of a composable file. State there is global state:
✕ Rejectedno-mutable-global
ts
import { ref } from "vue";
const count = ref(0);
export function useCounter() {
const increment = (): void => {
count.value++;
};
return { count, increment };
}Every component calling useCounter() gets the same count, and so does the next test. Create the state inside the composable, so each call makes its own:
✓ Accepted0 diagnostics
ts
import { ref } from "vue";
export function useCounter(start = 0) {
const count = ref(start);
const increment = (): void => {
count.value++;
};
return { count, increment };
}For state the whole app shares (the signed-in user, a store), create it once at startup and provide it, as in State without globals:
✓ Accepted0 diagnostics
ts
import { type App, type InjectionKey, shallowRef } from "vue";
import type { Option } from "@evobug_com/safe-ts-std/result";
export function createSession() {
// Nobody is signed in until `signIn` runs.
const user = shallowRef<Option<string>>(undefined);
const signIn = (name: string): void => {
user.value = name;
};
return { user, signIn };
}
export type Session = ReturnType<typeof createSession>;
export const sessionKey: InjectionKey<Session> = Symbol("session");
// main.ts: installSession(app). In a component: injectRequired(sessionKey).
export function installSession(app: App): void {
app.provide(sessionKey, createSession());
}inject(sessionKey) alone is Session | undefined, so every component that needs the session starts with a check. injectRequired from @evobug_com/safe-ts-vue/inject returns a Result that says why when nothing was provided. Use it when the component can show something useful without the value.
When it can't, a missing provider is a mistake in how the app is put together. Write the setup with withInjection: it hands the value to your setup, which returns the render function.
✓ Accepted0 diagnostics
ts
import { defineComponent, h, type InjectionKey, provide, type Ref, ref } from "vue";
import { withInjection } from "@evobug_com/safe-ts-vue/inject";
export type Cart = { readonly count: Ref<number> };
export const cartKey: InjectionKey<Cart> = Symbol("cart");
export const CartRoot = defineComponent({
setup(_, { slots }) {
provide(cartKey, { count: ref(0) });
return () => slots.default?.();
},
});
export const CartBadge = defineComponent({
setup() {
return withInjection(cartKey, (cart) => () => h("p", `${cart.count.value} items`));
},
});If nothing provides cartKey, CartBadge renders nothing and reports a MissingInjectionError naming the key: to app.config.errorHandler if the app has one, otherwise to console.error (Vue also warns in development). It doesn't throw. Vue runs setup with nothing of yours around it, so a PropagateError from there would be uncaught-propagation in every component (Errors). The function passed to withInjection runs during setup, so ref, computed, watch and onMounted work in it.
Pinia stores hold module state
A Pinia setup store's function runs once per Pinia instance: once in the app, and once in each test that creates its own Pinia. Its refs and lets belong to that instance, as in <script setup>, so no-mutable-global doesn't apply to them. In a Vue app that uses Pinia, a setup store is the usual home for state a module kept at its top level.
✕ Rejectedno-mutable-global
ts
import { ref } from "vue";
export const unread = ref(0);
export function markRead(count: number): void {
unread.value = Math.max(0, unread.value - count);
}The move is mechanical: the state goes into the store with the functions that change it. Readers get a computed, writers a function.
ts
// stores/inbox.ts
import { defineStore } from "pinia";
import { ref } from "vue";
export const useInboxStore = defineStore("inbox", () => {
const unread = ref(0);
function markRead(count: number): void {
unread.value = Math.max(0, unread.value - count);
}
return { unread, markRead };
});While callers still import unread from the old module, a module-level computed there is a bridge that keeps their unread.value working. A read-only computed is not state, so it is allowed. A writable one (computed({ get, set })) that other modules write is state again, and reported: export a function for writers, as here. The getter calls useInboxStore() when it is first read, which must be after app.use(pinia):
ts
// inbox.ts, until its callers use the store
import { computed } from "vue";
import { useInboxStore } from "./stores/inbox";
export const unread = computed(() => useInboxStore().unread);
export function markRead(count: number): void {
useInboxStore().markRead(count);
}Store members are followed like any function: an action declared to return a Result (async function load(): Promise<Result<void, LoadError>>) that a caller drops is must-use-result, through useDraftStore().load(), const store = useDraftStore(); store.load() and destructured members, in any file. An action that throws or rejects is followed into its callers the same way. Options stores' actions are followed too.
An event between modules that don't import each other
A module that has to react to something another one did (refresh the desk after a thread was read), where neither may import the other, needs a small store of its own, even for a counter. A hook on another store ($onAction) only fires while the call goes through that store's action, and stops firing without a word when the code moves to a plain function.
ts
// stores/threadEvents.ts: the only module both sides import
import { defineStore } from "pinia";
import { ref } from "vue";
export const useThreadEvents = defineStore("threadEvents", () => {
const reads = ref(0);
function threadRead(): void {
reads.value += 1;
}
return { reads, threadRead };
});
// The thread module, once the request succeeded:
// useThreadEvents().threadRead();
// The desk, in a component's setup or its own store:
// const events = useThreadEvents();
// watch(() => events.reads, () => refreshDesk());The counter changes on every event, so the watch runs for the second of two equal events too.
A store that reads itself while it is being built
Pinia registers a setup store before its function runs, and adds what the function returns after it returns. Code that runs during the setup and calls the same useX() (a request helper whose headers read useSessionStore().id, called by the session store's first request) gets the store without those fields: id is undefined, and the header is missing. Pass the value in from the setup's own variable instead of reading it back through the store, or start that request after the setup returned.
A Map in a store: keep it private
Pinia treats every ref and reactive object a setup store returns as state. It goes into $state, which $patch, devtools and persistence plugins read and write, and which serialises a Map as {}. A shallowReactive(new Map()) the store uses as a lookup table is better left out of the returned object, with functions to read and change it:
ts
// stores/drafts.ts
import { defineStore } from "pinia";
import { shallowReactive } from "vue";
import type { Option } from "@evobug_com/safe-ts-std/result";
export const useDraftsStore = defineStore("drafts", () => {
const drafts = shallowReactive(new Map<string, string>());
const draftOf = (id: string): Option<string> => drafts.get(id);
function saveDraft(id: string, text: string): void {
drafts.set(id, text);
}
return { draftOf, saveDraft };
});A computed in a component that calls drafts.draftOf(id) still updates, since the Map is reactive.
Props belong to the parent
defineProps() gives a component its parent's data, the way a function borrows a parameter. Changing it is no-param-mutation:
✕ Rejectedno-param-mutation
vue
<script setup lang="ts">
type User = { name: string; email: string };
const props = defineProps<{ user: User }>();
function clearEmail(): void {
props.user.email = "";
}
</script>
<template>
<input v-model="props.user.name" />
<button @click="clearEmail">Clear email</button>
</template>Vue makes the props object read-only, but not the objects inside it. props.user.email = "" works: it changes the parent's object behind its back, and the parent's code never hears about it. Tell the parent instead, with an event or defineModel():
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
const name = defineModel<string>("name", { required: true });
const emit = defineEmits<{ clearEmail: [] }>();
</script>
<template>
<input v-model="name" />
<button @click="emit('clearEmail')">Clear email</button>
</template>Setting a model's .value (which v-model does) asks the parent to update its data, and the parent decides. Destructuring in defineProps() itself (const { user } = defineProps<...>()) is fine: Vue compiles it so it stays reactive. Those names are the parent's data too.
A ref the parent hands over
Sometimes the parent passes a ref on purpose, for the child to write: a draft that a store-like object owns, a selection a dialog fills in. Say so in the props' type with Mut<Ref<T>>. That field is the child's to change; the rest of the props stays the parent's:
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import type { Ref } from "vue";
import type { Mut } from "@evobug_com/safe-ts-std/mut";
type Drafts = { readonly target: Mut<Ref<number>>; readonly title: string };
const props = defineProps<{ drafts: Drafts }>();
function choose(value: number): void {
props.drafts.target.value = value;
}
</script>
<template>
<h2>{{ props.drafts.title }}</h2>
<button @click="choose(1)">One</button>
</template>A Mut<Ref<number>> is a Ref<number> wherever one is read, so Vue and vue-tsc read the field as the ref it is. The parent lends it where it fills the field: const drafts = { target: mut(count), title: "Pick one" } (TypeScript refuses count without mut(...) there). The template unwraps a top-level ref of the parent's <script setup>: :target="count" passes the number, not the ref. Pass the ref inside an object (:drafts="drafts", as here), or as :target="drafts.target" from an object that holds it. A prop declared Mut<T> directly (defineProps<{ draft: Mut<Draft> }>()) is lent in the template, :draft="mut(draft)", with mut imported in <script setup> (templates don't see the prelude's names); missing-mut reports the binding without it. Where the parent would rather keep the change in its own hands, pass a function instead (setTarget(value), or an action of the store that owns the ref) and call that: nothing in the props is then changed at all.
Typed props in defineComponent and TSX
In a .vue file, defineProps<{ side?: "left" | "right" }>() gives props their types, and Vue compiles them into runtime declarations. Components written with defineComponent (TSX, render functions) declare props as objects. Vue's documented way to type one is a cast, which is no-unchecked-cast:
✕ Rejectedno-unchecked-cast
ts
import { defineComponent, h, type PropType } from "vue";
export const Panel = defineComponent({
props: {
side: { type: String as PropType<"left" | "right">, default: "left" },
},
setup(props) {
return () => h("aside", { class: props.side });
},
});prop and oneOf from @evobug_com/safe-ts-vue/prop build the same declaration with the type attached, so the cast stays inside the package:
✓ Accepted0 diagnostics
ts
import { defineComponent, h } from "vue";
import { oneOf, prop } from "@evobug_com/safe-ts-vue/prop";
type User = { readonly id: string; readonly name: string };
export const Panel = defineComponent({
props: {
title: prop<string>(String, { required: true }),
side: oneOf(["left", "right"], { default: "left" }),
users: prop<readonly User[]>(Array, { default: () => [] }),
collapsed: prop<boolean>(Boolean),
},
setup(props) {
// props.side: "left" | "right", props.users: readonly User[], props.collapsed: boolean
return () =>
h("aside", { class: props.side }, [
h("h2", props.title),
props.collapsed ? undefined : h("ul", props.users.map((user) => h("li", { key: user.id }, user.name))),
]);
},
});The same declarations work in TSX, and the parent is checked against them: <Panel title="Users" side="up" /> doesn't compile.
For TSX without Vue's Babel plugin (Vite with its own JSX transform, oxc), use @evobug_com/safe-ts-vue's JSX runtime: "jsx": "react-jsx" and "jsxImportSource": "@evobug_com/safe-ts-vue" in tsconfig.json, and the same import source in the bundler's JSX options. Vue's own vue/jsx-runtime hands a component its children as an array, which Vue turns into a default slot on every render, with a development warning each time; this one makes them the default slot function, as the Babel plugin does. Elements, fragments and Teleport keep their children, and an object of slot functions (default, actions, …) passes through. Its types are Vue's JSX, so no cast-free wrapper around h is needed.
prop<T>(constructor, options)takes the constructor Vue checks at runtime, and it must fitT:Stringfor strings and string literals,Number,Boolean,Array,Object,Function, or an array of them for a union (prop<string | number>([String, Number])).prop<number>(String)doesn't compile.{ required: true }makes the parent pass it.{ default }makes it always present in the component. Objects and arrays need a factory (() => []), so instances don't share one. Without either, the prop isT | undefined.prop<boolean>(Boolean)keeps Vue's Boolean casting: a missing prop isfalse, and<Panel collapsed />istrue. For a prop whose absence means something else, so a missing one must stay missing (aria-pressedonly on toggle buttons), writeprop<Option<boolean>>(Boolean, { default: undefined }): absent isundefined, notfalse.oneOf(values)is a prop that is one of a list of strings (or numbers). Its type is the union of the values, and itsvalidatorchecks the same list, so the two can't disagree.prop<"left" | "right">(String)only checks that the value is a string.
Vue checks the constructor and runs validator in development builds only, and warns rather than failing. Defaults and Boolean casting work in every build. The types are what TypeScript checks in the parent's code, the same promise defineProps<T>() makes.
The function form, defineComponent((props: { side?: "left" | "right" }) => ..., { props: ["side"] }), needs no cast either, but a list of names has no defaults and no Boolean casting.
Rules on this page: no-mutable-global, no-param-mutation, no-unchecked-cast, uncaught-propagation