File tree Expand file tree Collapse file tree 4 files changed +90
-0
lines changed
packages/svelte/tests/runtime-runes/samples/mount-component-in-onmount-with-context-with-state Expand file tree Collapse file tree 4 files changed +90
-0
lines changed Original file line number Diff line number Diff line change 1+ import { flushSync } from 'svelte' ;
2+ import { test } from '../../test' ;
3+
4+ export default test ( {
5+ test ( { assert, target, logs } ) {
6+ const button = target . querySelector ( 'button' ) ;
7+
8+ assert . htmlEqual (
9+ target . innerHTML ,
10+ `
11+ <button>toggle</button>
12+ <div>
13+ <p>First if block:</p>
14+ <span class="first">First: true</span>
15+ <p>Second if block:</p>
16+ <span class="second">Second: true</span>
17+ </div>
18+ `
19+ ) ;
20+
21+ flushSync ( ( ) => button ?. click ( ) ) ;
22+
23+ assert . htmlEqual (
24+ target . innerHTML ,
25+ `
26+ <button>toggle</button>
27+ <div>
28+ <p>First if block:</p>
29+ <p>Second if block:</p>
30+ </div>
31+ `
32+ ) ;
33+ }
34+ } ) ;
Original file line number Diff line number Diff line change 1+ <script >
2+ import { onMount } from ' svelte' ;
3+ import { mountComponentWithContext } from ' ./module.svelte.js' ;
4+
5+ let mountTarget;
6+
7+ let getShowText;
8+ let setShowText;
9+
10+ onMount (() => {
11+ const r = mountComponentWithContext (mountTarget);
12+ getShowText = r .getShowText ;
13+ setShowText = r .setShowText ;
14+ });
15+
16+ function toggleState () {
17+ setShowText (! getShowText ());
18+ }
19+ </script >
20+
21+ <button onclick ={() => toggleState ()}>toggle</button >
22+ <div bind:this ={mountTarget }></div >
Original file line number Diff line number Diff line change 1+ import { mount } from 'svelte' ;
2+ import Nested from './nested.svelte' ;
3+
4+ export function mountComponentWithContext ( target ) {
5+ const stateObject = $state ( { showText : true } ) ;
6+
7+ mount ( Nested , {
8+ target,
9+ props : { } ,
10+ context : new Map ( [ [ 'stateContext' , stateObject ] ] )
11+ } ) ;
12+
13+ return {
14+ getShowText : ( ) => stateObject . showText ,
15+ setShowText : ( newShowText ) => {
16+ stateObject . showText = newShowText ;
17+ }
18+ } ;
19+ }
Original file line number Diff line number Diff line change 1+ <script >
2+ import { getContext } from ' svelte' ;
3+
4+ const stateObjectFromContext = getContext (' stateContext' );
5+ </script >
6+
7+ <p >First if block:</p >
8+ {#if stateObjectFromContext .showText === true }
9+ <span class ="first" >First: {stateObjectFromContext .showText }</span >
10+ {/if }
11+
12+ <p >Second if block:</p >
13+ {#if stateObjectFromContext .showText === true }
14+ <span class ="second" >Second: {stateObjectFromContext .showText }</span >
15+ {/if }
You can’t perform that action at this time.
0 commit comments