Custom Pages
Add pages of your own as Vue files, give them props from the server, and read the site from your components.
A .vue file under src/pages is a page of your site, at the path of the file. This one is /about, with the navbar of your site from the home layout:
<script setup lang="ts">
import { definePage } from "vuesho/client";
import HomeLayout from "vuesho/layouts/home";
definePage({ data: { title: "About", description: "Who writes these docs." } });
</script>
<template>
<HomeLayout>
<main class="mx-auto w-full max-w-(--fd-layout-width) px-4 py-12">
<h1 class="text-2xl font-semibold">About</h1>
<p class="text-fd-muted-foreground">We write docs.</p>
</main>
</HomeLayout>
</template>definePage() has the options of the page. Its data sets the title and description of the page, which go to the <head> like those of a content page, so the title ends with the name of your site. A custom page is the one way to add a page of your own: the pages of your content render with the layouts of your theme, and a plugin adds pages with views.
A custom page renders on the server and hydrates in the browser, so use browser APIs only in onMounted() and event handlers. Its classes need to be in the stylesheet of your site: the compiled one has the classes that the UI uses, like the ones above, and Tailwind CSS adds the others.
Paths
index.vueis/, andblog/index.vueis/blog.about.vueis/about.blog/[slug].vuematches one segment, like/blog/hello.releases/v[version].vuematches a segment that starts withv, like/releases/v2. A name can have several params with text between them, like[pkg]-v[version].vue.[...path].vuematches every URL under its folder.
A file name that isn't a valid path, like [a][b].vue, fails with an error that names the file.
Files and folders starting with _ aren't pages, so they can hold the components of your pages. To use another folder than src/pages, set the pagesDir option of the Vite plugin, like vuesho({ pagesDir: "src/routes" }).
Params
A page with params, like showcase/[slug].vue, renders on demand at every path it matches, so it needs a deployment with a server. List its params in staticPaths to generate its pages at build time instead, and give each page its data with a function of the params:
<script setup lang="ts">
import { definePage, usePage } from "vuesho/client";
definePage({
staticPaths: ["vuesho", "fumapress"],
data: ({ params }) => ({ title: `Showcase: ${params.slug}` }),
});
const page = usePage();
</script>
<template>
<h1 v-if="page.kind === 'custom'">{{ page.params.slug }}</h1>
</template>staticPathslists the value of each param. A page with several params, like[pkg]-v[version].vue, takes objects by name:{ pkg: "vue", version: "3" }.datais the page data, or a function of{ params, lang, request }. It returnsundefinedfor a path without a page, which then shows the not found page.render: "dynamic"renders the listed pages on demand too, andrender: "static"generates a page without params at build time, which is the default. A page with params andrender: "static"needsstaticPaths, or the site fails to start, naming its file.
With staticPaths, a page renders only the paths it lists, on a server as on a static host.
Props
props gives the component of the page data from the server, like a list of posts. The component receives them as its props, and declares them with defineProps():
<script setup lang="ts">
import { definePage, Link } from "vuesho/client";
import { listPosts, type Post } from "../../server/posts";
definePage({
data: { title: "Blog" },
props: async (): Promise<{ posts: Post[] }> => ({ posts: await listPosts() }),
});
defineProps<{ posts: Post[] }>();
</script>
<template>
<Link v-for="post in posts" :key="post.url" :href="post.url">{{ post.title }}</Link>
</template>propsis an object of props by name, or a function of{ params, lang, request }, likedata. The function returnsundefinedfor a path without a page, which then shows the not found page.- The props are sent to the browser as JSON, so every value must be serializable: a
Dateis a string in the component.usePage()has them inpage.propstoo. - The function runs on the server only, and in the build for a page generated at build time. The browser receives the props with the page on a navigation.
To read your content in props, call getSiteContext() of vuesho/config, the context of the site. definePage<typeof app>() types lang with the languages of your site, through a type-only import of vuesho.config.ts:
import { getSiteContext, type SiteLang } from "vuesho/config";
import type app from "../../vuesho.config";
export function listPosts(lang: SiteLang<typeof app>) {
return getSiteContext<typeof app>()
.getPages(lang)
.flatMap((page) => (page.type === "blog" ? [{ title: page.data.title, url: page.url }] : []));
}<script setup lang="ts">
import { definePage } from "vuesho/client";
import { listPosts } from "../../server/posts";
import type app from "../../../vuesho.config";
definePage<typeof app>({
data: { title: "Blog" },
props: ({ lang }) => ({ posts: listPosts(lang) }),
});
</script>Server Code
definePage() is a macro. The build compiles the call out of the component, into a module that the server reads when the site starts. So the data and props functions, and a module that only the call imports, stay on the server:
<script setup lang="ts">
import { definePage, usePage } from "vuesho/client";
import { getPosts } from "../../server/posts";
definePage({
staticPaths: async () => (await getPosts()).map((post) => post.slug),
data: async ({ params }) => {
const post = (await getPosts()).find((each) => each.slug === params.slug);
return post && { title: post.title };
},
});
const page = usePage();
</script>
<template>
<h1>{{ page.pageData.title }}</h1>
</template>The browser receives the page data that data returns, not getPosts or its module. An import stays in the component too when the rest of the file names it, in the script, the template or a style, like the type of the props in defineProps().
The call has a fixed shape, and the build fails with the file and the line when a page breaks it:
- A page has one call, written as a statement at the top level of
<script setup>or<script>. - The argument is an object literal.
- The argument uses imports and the variables it declares itself. It can't use a variable of the component, since it runs outside the component.
- Only the
.vuefile of a page calls it, not a component or a file starting with_.
Languages
On a site with languages, a custom page exists in each of them, at the prefix of the language: about.vue is /about and /cn/about. Read the language with useSite().lang to translate its texts.
A page in one language, like a landing page you don't translate, sets lang:
<script setup lang="ts">
import { definePage } from "vuesho/client";
definePage({ lang: "en", data: { title: "Acme Docs" } });
</script>lang: false keeps the page at its path as written, outside the languages: legal.vue is only /legal.
Which Page Renders a URL
A URL has one page. The most specific one renders it:
- An exact path: a custom page without params, a page listed in
staticPaths, or a content page. - A path with params, ranked segment by segment: a fixed segment, then text with a param, then a param, then a rest param.
So [...path].vue renders the URLs nothing else has, in place of the not found page. A custom page and a content page at the same URL fail when the site starts, naming both, so a page is never hidden by another one without you knowing. A dynamic source can gain a page at any path while the server runs, so its page yields to the custom page instead. A custom page at the path of a view of a plugin replaces it, which is how you change a page of a plugin.
Not Found Page
The not found page of a language is the page at /404, at /cn/404 for cn. It renders with the status 404 at every URL that has no page. By default, it is the NotFound component of your theme. To replace it, add src/pages/404.vue, which then exists in each language:
<script setup lang="ts">
import { definePage } from "vuesho/client";
import HomeLayout from "vuesho/layouts/home";
definePage({ data: { title: "Not Found" } });
</script>
<template>
<HomeLayout><main>This page doesn't exist.</main></HomeLayout>
</template>The not found page has noindex, so it stays out of the sitemap and search engines. The build writes it as 404.html, and as cn/404.html for each language with a prefix, which static hosts serve at a URL without a file.
Composables
vuesho/client has the composables that read the app, in a custom page or in any component of your site. Each one returns a ref, except useRoute(), which returns a reactive object like the route of Vue Router:
usePage(): the page on screen, on every page. Itskindiscontent,view,customornot-found, and every kind hasurlandpageData. A custom page has itsparams, like a view, and itsprops.usePage<typeof app>()types it as one of the pages of your site, which narrow bykindandtype.useRoute(): the route of the page on screen: itspathwithout the base path,query,hash,paramsandhref, the URL in the address bar.useRouter(): the router.push()andreplace()go to a path of the site,resolve(path)?.hrefis the URL of a page with the base path, andbeforeEach()andafterEach()add router hooks.useSite(): thenameanddescriptionof the site in the language of the page,lang, the key of that language, anddir, the direction of its text.usePageTree(): the page tree of the language of the page.useColorMode(): the color mode.useDataRoute(path): the value of a data route.
Link links to a page of the site with client-side navigation, and opens other URLs in a new tab. It loads the page when the reader points at the link, so the navigation doesn't wait for it, unless you set :prefetch="false". This page links to the pages at the top of the page tree:
<script setup lang="ts">
import { computed } from "vue";
import { Link, usePageTree } from "vuesho/client";
const tree = usePageTree();
const pages = computed(() => tree.value.children.filter((node) => node.type === "page"));
</script>
<template>
<nav>
<Link v-for="page in pages" :key="page.url" :href="page.url">{{ page.name }}</Link>
</nav>
</template>A path of the site is written without the base path, and Link adds it. For other URLs of your site, like an image in public, withBase("/logo.png") adds the base path.
ClientOnly renders its default slot in the browser only, once the app is mounted, and its fallback slot on the server. Wrap a component that can't render on the server in it.
A page generated at build time is rendered without a query, whatever the URL the reader opens it with. To show something that depends on useRoute().query on such a page, render it inside ClientOnly too, so the first render in the browser matches the HTML of the build.
Color Mode
useColorMode() returns preference, the reader's choice of "light", "dark" or "system", and isDark, whether the page is dark. Setting preference applies the choice and keeps it for the next visits:
<script setup lang="ts">
import { useColorMode } from "vuesho/client";
const { preference, isDark } = useColorMode();
</script>
<template>
<button type="button" @click="preference = isDark ? 'light' : 'dark'">
Switch the color mode
</button>
</template>The reader's choice is kept in the browser, so both are undefined on the server and until the app is mounted. A color mode that ui.colorMode fixes is known on the server too, and setting preference then throws. The class dark of <html> is set before the page shows, so style the dark mode with the .dark selector, and use isDark for what only code can do.
Vue Plugin Options
The Vite plugin sets up @vitejs/plugin-vue for your .vue files. Its vue option takes the options of the Vue plugin, which are added to the ones Vuesho sets, like the custom elements of your templates. Its template.compilerOptions apply to the pages of your content too:
import { defineConfig } from "vite";
import vuesho from "vuesho/vite";
export default defineConfig({
plugins: [
vuesho({
vue: {
template: { compilerOptions: { isCustomElement: (tag) => tag.startsWith("x-") } },
},
}),
],
});