0.1.4 ⢠Published 5 years ago
svelte-one-component-router v0.1.4
Svelte One Component Router
Lightweight minimalistic svelte router in one component
š Docs
š Getting started
Just download this file to your project folder and import it to the component you need:
<script>
import Route, { router } from './components/Router.svelte';
</script>
š Navigation
You can navigate with:
- native link element
<a href="/path">...</a>
- or navigate router method
router.push(path)
external
atribute in link prevents SPA routing.
Example:
<a href="/test">Go to '/test' route</a>
<a href="https://example.com" external>Go to external route</a>
<button on:click={() => router.push('/test')}> // By default replaceState = false
Go to '/test' route
</button>
š Route component
Default properties:
<Route
fallback={false}
path="/" />
Example of App.svelte
:
<script>
import Route, { router } from './components/Router.svelte'
</script>
<nav>
<a href="/">Home</a>
<a href="/portfolio">Portfolio</a>
<a href="/contacts">Contacts</a>
</nav>
<Route>
<Route path="/">
<h1>It is main page</h1>
</Route>
<Route path="/portfolio">
<Route path="/">
<h1>Portfolio home</h1>
</Route>
<Route path="/sites">
<h1>Portfolio: Sites</h1>
</Route>
<Route path="/apps">
<h1>Portfolio: Apps</h1>
</Route>
<Route fallback title="Portfolio 404">
<h1>404: fallback from portfolio</h1>
</Route>
<nav>
<a href="/portfolio">Home</a>
<a href="/portfolio/sites">Sites</a>
<a href="/portfolio/apps">Apps</a>
</nav>
</Route>
<Route path="/contacts" title="Contacts">
<h1>Contacts</h1>
</Route>
<Route fallback title="404">
<h1>404: fallback</h1>
</Route>
</Route>
ā Anti-patterns
Invalid path
ā Anti-pattern:
<Route path="path" />
ā Do this:
<Route path="/path" />
Fallback not in Route
ā Anti-pattern:
<Route path="/">
...
</Route>
<Route fallback />
ā Do this:
<Route>
<Route path="/" />
...
<Route fallback />
</Route>
Route in fallback
ā Anti-pattern:
<Route fallback>
<Route path="/" />
</Route>
ā Don't place other routes in fallback