6. svelte homepage https://svelte.dev

최종 업데이트 : 2025-01-27

shadcn을 적용했음으로 똑같이 나오려면 해당 준비까지 하시고 따라하시면 좋습니다.

tauri도 적용되어있으니 앱이나 데스크탑으로도 실행해보세요.

      
        
src/routes/+page.svelte

<script>
  import { writable } from 'svelte/store';
  import { Button } from '$lib/components/ui/button';
  import { Input } from '$lib/components/ui/input';
  import { Label } from '$lib/components/ui/label';

  const id = writable('');
  const password = writable('');
  const passwordCheck = writable('');

  async function signupRequest() {
    try {
      const response = await fetch('http://localhost:8000/api/signup', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          id: $id,
          password: $password,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        alert(`${data.status_code} ${data.content}`);
      } else {
        const errorData = await response.json();
        alert(`${errorData.status_code} ${errorData.content}`); 
      }
    } catch (e) {
      console.error(e);
      alert(`Error: ${e}`);
    }
  }
</script>


<main class="flex flex-col items-center justify-center min-h-screen bg-gray-50">
  <div class="bg-white p-6 rounded-lg shadow-md w-full max-w-md">
    <h1 class="text-2xl font-bold mb-4 text-center">회원가입</h1>
    <form>
      <Label for="id" class="block text-gray-700">아이디</Label>
      <Input id="id" bind:value={$id} class="w-full mb-4" />

      <Label for="password" class="block text-gray-700">패스워드</Label>
      <Input type="password" id="password" bind:value={$password} class="w-full mb-4" />

      <Label for="passwordCheck" class="block text-gray-700">패스워드 확인</Label>
      <Input type="password" id="passwordCheck" bind:value={$passwordCheck} class="w-full mb-6" />

      <Button on:click={signupRequest} class="w-full bg-indigo-500 text-white hover:bg-indigo-600">회원가입</Button>
    </form>
  </div>
</main>
  
      
    

svelte5가 나온지 얼마 안되었음으로 맛보기로 스벨트4로 작성했습니다.

다음 학습자료부턴 svelte5로 코드를 변경하여 작성하겠습니다.

Runes를 사용하면 문법이 조금 더 리액트스러워집니다.

    
      
import { writable } from 'svelte/store';

const id = writable('');
const password = writable('');
const passwordCheck = writable('');
    
    
  

svelte에서 지원하는 store인 writable를 사용하도록 선언합니다.

혹시나 실수로 변수에 재할당을 방지하기 위해 const로 선언하여 각 변수들을 초기화해줍니다.

    
      
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label';
    
    
  

shadcn의 Button, Input, Label을 선언합니다.

    
      
<main class="flex flex-col items-center justify-center min-h-screen bg-gray-50">
<div class="bg-white p-6 rounded-lg shadow-md w-full max-w-md">
  <h1 class="text-2xl font-bold mb-4 text-center">회원가입</h1>
  <form>
    <Label for="id" class="block text-gray-700">아이디</Label>
    <Input id="id" bind:value={$id} class="w-full mb-4" />

    <Label for="password" class="block text-gray-700">패스워드</Label>
    <Input type="password" id="password" bind:value={$password} class="w-full mb-4" />

    <Label for="passwordCheck" class="block text-gray-700">패스워드 확인</Label>
    <Input type="password" id="passwordCheck" bind:value={$passwordCheck} class="w-full mb-6" />

    <Button on:click={signupRequest} class="w-full bg-indigo-500 text-white hover:bg-indigo-600">회원가입</Button>
  </form>
</div>
</main>
      
    
  

스벨트는 스크립트 구문과 html구문 그리고 스타일구문으로 나뉩니다.

tailwind와 shadcn을 사용함으로 필요하지않다면 별도로 스타일구문은 작성하지 않습니다.

tailwind같은 경우는 써보시면서 익숙해져야함으로 넘어가겠습니다.

스벨트는 html구문에 bind:value로 스크립트 구문을 연결할 수 있습니다.

input type 컨트롤에 선언하여 입력값을 스토어를 통해 사용할 수 있습니다.

스벨트는 이벤트를 사용할 때 on:click과 같이 사용합니다.

이벤트를 사용할 때는 함수를 선언하여 사용합니다.

    
      
async function signupRequest() {
try {
  const response = await fetch('http://localhost:8000/api/signup', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      id: $id,
      password: $password,
    }),
  });

  if (response.ok) {
    const data = await response.json();
    alert(`${data.status_code} ${data.content}`);
  } else {
    const errorData = await response.json();
    alert(`${errorData.status_code} ${errorData.content}`); 
  }
} catch (e) {
  console.error(e);
  alert(`Error: ${e}`);
}
}
      
    
  

간단한 signupRequest 함수를 작성하였습니다.

fetch를 사용하여 post요청을 보내고 응답을 받아오는 코드입니다.

response.ok가 true일 경우와 false일 경우를 나누어 alert를 띄웁니다.

catch로 에러를 잡아서 console.error로 에러를 출력하고 alert로 에러를 띄웁니다.

이렇게 간단하게 fetch를 사용할 수 있습니다.

fetch는 promise를 반환하기 때문에 async await를 사용하여 비동기로 처리합니다.

fetch는 json으로 응답을 받기 때문에 response.json()을 사용하여 json으로 변환합니다.

json으로 변환된 데이터를 사용할 수 있습니다.

script 구문과 html 구문 둘다 변수를 $를 이용함으로 사용할 수있습니다.

react같은 별도의 jsx문법을 사용할 필요가 없고 simple함이 장점입니다.

Related Pages

© 2024 Coding Stairs. All rights reserved.