Skip to main content

Phần tử <svelte:fragment> cho phép bạn đặt nội dung trong một khe (slot) có tên mà không cần bọc nó trong một phần tử DOM container.

Trong bài tập này, chúng ta đang tạo một trò chơi Tic-Tac-Toe. Để tạo lưới, các phần tử <button> trong App.svelte nên là con trực tiếp của phần tử <div class="board"> trong Board.svelte.

Hiện tại, nó chưa thành hình vì chúng là con của <div slot="game">. Hãy sửa nó:

App.svelte
<svelte:fragment slot="game">
	{#each squares as square, i}
		<button
			class="square"
			class:winning={winningLine?.includes(i)}
			disabled={square}
			on:click={() => {
				squares[i] = next;
				next = next === 'x' ? 'o' : 'x';
			}}
		>
			{square}
		</button>
	{/each}
</svelte:fragment>

Tiếp theo: Module context

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<script>
	import Board from './Board.svelte';
	import { getWinningLine } from './utils.js';
 
	let squares = Array(9).fill('');
	let next = 'x';
 
	$: winningLine = getWinningLine(squares);
</script>
 
<div class="container">
	<Board size={3}>
		<div slot="game">
			{#each squares as square, i}
				<button
					class="square"
					class:winning={winningLine?.includes(i)}
					disabled={square}
					on:click={() => {
						squares[i] = next;
						next = next === 'x' ? 'o' : 'x';
					}}
				>
					{square}
				</button>
			{/each}
		</div>
 
		<div slot="controls">
			<button on:click={() => {
				squares = Array(9).fill('');
				next = 'x';
			}}>
				Reset
			</button>
		</div>
	</Board>
</div>
 
<style>
	.container {
		display: flex;
		flex-direction: column;
		gap: 1em;
		align-items: center;
		justify-content: center;
		height: 100%;
		margin: 0 auto;
	}
 
	.square, .square:disabled {
		background: white;
		border-radius: 0;
		color: #222;
		opacity: 1;
		font-size: 2em;
		padding: 0;
	}
 
	.winning {
		font-weight: bold;
	}
 
	.container:has(.winning) .square:not(.winning) {
		color: #ccc;
	}
</style>
initialising