Skip to content

Provide and inject ​

provide and inject: context a component hands every component below it.

The compiler sees the whole component tree, so it resolves each inject to what an ancestor provides while the page renders. Every component that provides or injects something, or renders one that does, takes a Provides after its other parameters (only a &Head comes after it): one field per key, None where no ancestor provides it. A component that provides overlays its values on the Provides it was given and hands the result to its children and to the content of its slots.

ts
// types/keys.ts
import type { InjectionKey } from "vue";

export const ThemeKey: InjectionKey<string> = Symbol("theme");
vue
<!-- Toolbar.vue -->
<script setup lang="ts">
import { provide } from "vue";
import { ThemeKey } from "../types/keys";

const props = defineProps<{ theme: string }>();
provide(ThemeKey, props.theme);
</script>

<template>
  <nav class="toolbar"><slot /></nav>
</template>

<!-- ThemedButton.vue -->
<script setup lang="ts">
import { inject } from "vue";
import { ThemeKey } from "../types/keys";

defineProps<{ label: string }>();
const theme = inject(ThemeKey, "light");
</script>

<template>
  <button :class="['btn', theme]">{{ label }}</button>
</template>
rust
use generated::{provides::Provides, themed_button, toolbar};

// Nothing provides `ThemeKey`, so `inject` gives its default.
let mut out = String::new();
themed_button::render(&mut out, &themed_button::Props::new("Save"), Provides::default());
assert_eq!(out, r#"<button class="btn light">Save</button>"#);

// What the client app gives `app.provide`, the page is rendered with.
out.clear();
themed_button::render(&mut out, &themed_button::Props::new("Save"), Provides { theme_key: Some("dark") });
assert_eq!(out, r#"<button class="btn dark">Save</button>"#);

// Slot content written in Rust is handed what the toolbar provides.
let content: &toolbar::DefaultSlot = &|out: &mut String, provides: Provides<'_>| {
    themed_button::render(out, &themed_button::Props::new("Save"), provides);
    true
};
out.clear();
toolbar::render(&mut out, &toolbar::Props::new("ocean"), toolbar::Slots { default: Some(content) }, Provides::default());
assert_eq!(out, r#"<nav class="toolbar"><!--[--><button class="btn ocean">Save</button><!--]--></nav>"#);
#[derive(Debug, Clone, Copy, Default)]
pub struct Provides<'p> {
    /// What is provided under `ThemeKey`, exported from `types/keys.ts`.
    pub theme_key: Option<&'p str>,
}
pub fn render(out: &mut String, props: &Props<'_>, fv_provides: super::provides::Provides<'_>) {
    out.reserve(
        29
        + props.label.len()
    );
    out.push_str("<button class=\"btn");
    fv::attrs::class_into(out, true, &[fv_provides.theme_key.unwrap_or("light")]);
    out.push_str("\">");
    fv::core::escape_into(out, &props.label);
    out.push_str("</button>");
}
pub type DefaultSlot<'s> = dyn Fn(&mut String, super::provides::Provides<'_>) -> bool + 's;
pub fn render(out: &mut String, props: &Props<'_>, fv_slots: Slots<'_>, _fv_provides: super::provides::Provides<'_>) {
    out.reserve(
        27
        + props.theme.len()
    );
    let fv_provides = super::provides::Provides { theme_key: Some(&props.theme) };
    out.push_str("<nav class=\"toolbar\">");
    fv::render::scoped_slot_into(out, fv_slots.default.map(|f| move |out: &mut String, _: &()| f(out, fv_provides)).as_ref(), &(), None);
    out.push_str("</nav>");
}

Keys ​

A key is a string literal (provide("theme", …)), or a Symbol exported from one of the project's .ts files and typed InjectionKey<T>:

ts
export const ThemeKey: InjectionKey<string> = Symbol("theme");
export const TabsKey = Symbol("tabs") as InjectionKey<TabsState>;

A symbol's type is its T. A string key's type is the type argument of an inject (inject<number>("size")), or the type of its default, and every provide of it must agree. An InjectionKey<Ref<T>> holds T, provided as a ref; an InjectionKey of a function type is client-only (below).

Values ​

What a component provides is anything its render computes: a prop, a ref, a computed, a constant, or an object of those under an InjectionKey<T> whose T is an interface from a shared .ts file. A ref inside an object is unwrapped only by reactive(), as Vue does: provide(TabsKey, reactive({ active, count: props.count })).

A value is never null or undefined: inject hands such a value on as it is, where its default would apply without a provider, so fall back with ?? before providing it.

What inject returns has the key's type, or is undefined without a provider and a default: read it with ?. (tabs?.active). A default is a value of the key's type (inject(ThemeKey, "light")), or a factory with true (inject("tone", () => "plain", true)). Under a key whose type is an interface, the default may be an object of it, given as it is or returned by a factory: inject(LookKey, { size: "md", tone: props.tone }) or inject(LookKey, () => ({ size: "md", tone: "plain" }), true). Its fields are values the render computes, as in a provided object, an optional field may be left out, and the render builds the object once and reads it wherever no ancestor provides the key. Where the key is provided as a ref the default is a ref too (inject(CountKey, ref(0))), so that .value reads the same with a provider and without one.

A key whose value is a function (provide(SelectKey, (name: string) => …)) is client-only: what inject returns may be called from event handlers, which the server drops, and the Provides has no field for it. Provide state and functions under keys of their own.

Slots ​

Vue resolves inject through the component tree, so content in a slot sees what the component that renders the slot provides, as well as everything above it. A component that takes a Provides hands it to each slot's content: its slot types take a Provides after their other arguments, as in the example above. Content filled from Rust passes it on to the components it renders.

Rendering from Rust ​

A page that starts the render passes Provides::default(), or the values its client app provides with app.provide: Vue's client gives a component the app's values where no ancestor provides the key, and the server must render with the same ones to hydrate without a mismatch. A component that takes a Provides has no island(): an island is mounted as an app of its own, which provides nothing, so hydrate it from the page's app instead.

A component holding <RouterView> may not provide anything: the page it shows is rendered from Rust and handed in as a slot. Pass the page the same Provides the layout was given.

What is refused ​

  • a key that is not a string literal or an exported Symbol, and a symbol without InjectionKey<T>;
  • provide and inject anywhere but at the top of <script setup>, and destructuring what inject returns;
  • inject(key)!, which asserts a provider that a render without one breaks;
  • a function given as a default without true;
  • values of different types, a ref and a plain value, or a function and a value under one key;
  • a value that may be null or undefined, a list computed in place (provide a computed of it), a ref in a plain object, and an object under a key without an interface, provided or given as a default;
  • a key provided twice by one component, and two keys whose fields in Provides would share a name;
  • setup that assigns to an injected value, which the components rendered before it would show unchanged;
  • a string-keyed inject inside a Rust twin's slot, whose library component may provide the same key on the client;
  • a provide(…) not imported from vue, a call in setup that could change what renders (FV0105).

error_codes lists their codes, under FV16xx and FV0105.