SeouliteLab

[Vue.js] Vue 컴포넌트를 등록하는 app.component() 메서드 이해하기 본문

카테고리 없음

[Vue.js] Vue 컴포넌트를 등록하는 app.component() 메서드 이해하기

Seoulite Lab 2024. 4. 25. 08:07

Vue.js에서는 재사용 가능한 컴포넌트를 생성하고 등록하기 위해 app.component() 메서드를 사용합니다. 이 메서드를 사용하여 Vue 애플리케이션 내에서 컴포넌트를 정의하고 등록할 수 있습니다.

app.component() 메서드란?

app.component() 메서드는 Vue 애플리케이션 내에서 컴포넌트를 등록하기 위해 사용됩니다. 이를 통해 애플리케이션에서 여러 번 사용되는 컴포넌트를 한 번 정의하고 필요할 때마다 재사용할 수 있습니다.

예제

아래는 app.component() 메서드를 사용하여 간단한 Vue 컴포넌트를 등록하는 예제입니다.

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue 컴포넌트 등록 예제</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>
<body>

<div id="app">
  <my-component></my-component>
</div>

<script>
  const app = Vue.createApp({});

  // 컴포넌트 등록
  app.component('my-component', {
    template: '<p>안녕하세요, 이것은 Vue 컴포넌트입니다.</p>'
  });

  // 애플리케이션을 #app 요소에 마운트
  app.mount('#app');
</script>

</body>
</html>

위 예제에서는 다음과 같은 작업을 수행합니다.

  1. createApp() 메서드를 사용하여 Vue 애플리케이션을 생성합니다.
  2. app.component() 메서드를 사용하여 컴포넌트를 등록합니다. 이때 첫 번째 인자는 컴포넌트의 이름을 나타내는 문자열이며, 두 번째 인자는 컴포넌트의 옵션을 포함하는 객체입니다.
  3. 등록된 컴포넌트를 Vue 애플리케이션에서 사용합니다.