So far, we've dealt exclusively with internal state — that is to say, the values are only accessible within a given component.
In any real application, you'll need to pass data from one component down to its children. To do that, we need to declare properties, generally shortened to 'props'. In Svelte, we do that with the export
keyword. Edit the Nested.svelte
component:
<script>
export let answer;
</script>
Just like
$:
, this may feel a little weird at first. That's not howexport
normally works in JavaScript modules! Just roll with it for now — it'll soon become second nature.
App.svelte
Nested.svelte
9
1
2
3
4
5
6
›
⌄
<script>
import Nested from './Nested.svelte';
</script>
<Nested answer={42} />
- "<Nested> was created with unknown prop 'answer'"
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
›
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
⌄
/* App.svelte generated by Svelte v4.2.19 */
import {
SvelteComponent,
create_component,
destroy_component,
init,
mount_component,
noop,
safe_not_equal,
transition_in,
transition_out
} from "svelte/internal";
import "svelte/internal/disclose-version";
import Nested from './Nested.svelte';
function create_fragment(ctx) {
let nested;
let current;
nested = new Nested({ props: { answer: 42 } });
return {
c() {
create_component(nested.$$.fragment);
},
m(target, anchor) {
mount_component(nested, target, anchor);
current = true;
},
p: noop,
i(local) {
if (current) return;
transition_in(nested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(nested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(nested, detaching);
}
};
}
class App extends SvelteComponent {
constructor(options) {
super();
init(this, options, null, create_fragment, safe_not_equal, {});
}
}
export default App;
result = svelte.compile(source, {
generate:
css:
});9
1
›
/* Add a <style> tag to see compiled CSS */