Reputation: 75
How to pass data (ex: Navbar Title) to a component used in the parent element?
<!-- _layout.svelte -->
<script>
import Nav from "../components/Nav.svelte";
let navTitle = "MyApp";
</script>
<Nav {navTitle}/>
<slot />
<!-- Nav.svelte -->
<script>
export let navTitle = "";
</script>
<h1>{navTitle}</h1>
<!-- Login.svelte -->
How to pass navTitle value from here to Nav.svelte?
To clarify, this needs to be scalable and to work on page load/transition for all routes of an SPA using Routify, preferably providing a default value and be able to have HTML value:
<!-- Article.svelte -->
<!-- User.svelte -->
navTitle is '<a href="/user">My Account </a>'
<!-- Comment.svelte -->
Upvotes: 7
Views: 4958
Reputation: 485
Check out this example in case you need to communicate between sibling elements but you need the shared data to be specific to each group of sibling components.
Upvotes: 0
Reputation: 16411
The easiest way to share data across components is to use stores as described in the docs
Your setup for that would be
<!-- Nav.svelte -->
<script>
import { navTitle } from './store.js'
</script>
<h1>{$navTitle}</h1>
<!-- Login.svelte -->
<script>
import { navTitle } from './store.js'
navTitle.set('...')
</script>
<!-- store.js -->
import { writable } from 'svelte/store'
export const navTitle = writable('')
Upvotes: 9
Reputation: 2149
You can pass a function to Login.svelte
component
<script>
import Nav from "./Nav.svelte";
import Login from "./Login.svelte"
let navTitle = "MyApp";
const onlogin= (v)=>navTitle = v
</script>
<Login {onlogin}/>
<Nav {navTitle}/>
And call the passed function in the Login.svelte
<script>
export let onlogin
</script>
<p on:click={()=>onlogin("Logged in")}>
click me to login
</p>
Here is the REPL: https://svelte.dev/repl/f1c8777df93f414ab26734013f2c4789?version=3
There are other (better) ways to do this like:
createEventDispatcher
setContext
, getContext
)Upvotes: 1