<Vue.js> 컴포넌트

2024. 8. 19. 00:10Front-End/Vue.js

반응형

컴포넌트

Vue.js 컴포넌트에 대한 전체적인 설명을 제공하겠습니다. 컴포넌트는 Vue.js 애플리케이션을 구성하는 기본 단위로, 독립적이고 재사용 가능한 코드 블록입니다. 컴포넌트는 HTML, CSS, 자바스크립트 코드를 한 곳에 모아서 재사용성을 높이고 코드를 모듈화합니다.

1. 컴포넌트의 기본 구조

Vue.js 컴포넌트는 보통 .vue 파일로 정의되며, 각 파일은 세 부분으로 구성됩니다:

  • <template>: 컴포넌트의 HTML 구조를 정의합니다.
  • <script>: 컴포넌트의 로직을 정의합니다.
  • <style>: 컴포넌트의 스타일을 정의합니다.

예제 (MyComponent.vue):

<template>
  <div class="my-component">
    <h1>{{ title }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: 'Hello, Vue!'
    };
  }
}
</script>

<style scoped>
.my-component {
  color: blue;
}
</style>

 

2. 컴포넌트 등록

컴포넌트를 사용하려면 먼저 등록해야 합니다. 등록 방법은 전역 등록과 지역 등록으로 나뉩니다.

전역 등록

전역 등록은 Vue 애플리케이션의 모든 부분에서 사용할 수 있습니다.

main.js:

import Vue from 'vue';
import App from './App.vue';
import MyComponent from './components/MyComponent.vue';

Vue.component('my-component', MyComponent);

new Vue({
  render: h => h(App),
}).$mount('#app');

지역 등록

지역 등록은 특정 컴포넌트에서만 사용할 수 있습니다.

ParentComponent.vue:

<template>
  <div>
    <my-component></my-component>
  </div>
</template>

<script>
import MyComponent from './MyComponent.vue';

export default {
  components: {
    MyComponent
  }
}
</script>

3. 컴포넌트 간 통신

Props

부모 컴포넌트가 자식 컴포넌트에 데이터를 전달할 때 사용됩니다.

자식 컴포넌트 (ChildComponent.vue):

<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>

<script>
export default {
  props: {
    message: String
  }
}
</script>

부모 컴포넌트 (ParentComponent.vue):

<template>
  <div>
    <child-component message="Hello from Parent!"></child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  }
}
</script>

 

이벤트

자식 컴포넌트가 부모 컴포넌트에 메시지를 전달할 때 사용됩니다.

자식 컴포넌트 (ChildComponent.vue):

<template>
  <button @click="notifyParent">Notify Parent</button>
</template>

<script>
export default {
  methods: {
    notifyParent() {
      this.$emit('notify', 'Hello from Child!');
    }
  }
}
</script>

 

부모 컴포넌트 (ParentComponent.vue):

<template>
  <div>
    <child-component @notify="handleNotify"></child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  methods: {
    handleNotify(message) {
      console.log(message);
    }
  }
}
</script>

 

4. 슬롯

슬롯은 부모 컴포넌트가 자식 컴포넌트에 콘텐츠를 삽입할 수 있게 합니다. 기본 슬롯, 명명된 슬롯, 스코프 슬롯으로 나뉩니다.

기본 슬롯

자식 컴포넌트:

<template>
  <div>
    <slot></slot>
  </div>
</template>

 

부모 컴포넌트:

<template>
  <child-component>
    <p>This is a slot content.</p>
  </child-component>
</template>

명명된 슬롯

자식 컴포넌트:

<template>
  <div>
    <slot name="header"></slot>
    <slot></slot>
    <slot name="footer"></slot>
  </div>
</template>

부모 컴포넌트:

<template>
  <child-component>
    <template v-slot:header>
      <h1>Header Content</h1>
    </template>
    <p>Main Content</p>
    <template v-slot:footer>
      <footer>Footer Content</footer>
    </template>
  </child-component>
</template>

 

스코프 슬롯

자식 컴포넌트:

<template>
  <div>
    <slot :message="message"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello from Child'
    }
  }
}
</script>

부모 컴포넌트:

<template>
  <child-component>
    <template v-slot:default="slotProps">
      <p>{{ slotProps.message }}</p>
    </template>
  </child-component>
</template>

5. 컴포넌트 생명주기

Vue 컴포넌트는 여러 생명주기 훅을 통해 컴포넌트가 생성, 업데이트, 소멸되는 동안 특정 로직을 실행할 수 있습니다.

  • beforeCreate: 컴포넌트 인스턴스가 초기화된 직후
  • created: 컴포넌트가 생성된 후
  • beforeMount: 컴포넌트가 DOM에 마운트되기 직전
  • mounted: 컴포넌트가 DOM에 마운트된 후
  • beforeUpdate: 데이터 변경 후 DOM 업데이트 전
  • updated: 데이터 변경 후 DOM 업데이트 후
  • beforeDestroy: 컴포넌트가 제거되기 직전
  • destroyed: 컴포넌트가 제거된 후

예제:

<script>
export default {
  created() {
    console.log('Component Created');
  },
  mounted() {
    console.log('Component Mounted');
  },
  destroyed() {
    console.log('Component Destroyed');
  }
}
</script>

 

6. 고급 기능

컴포지션 API

Vue 3부터 도입된 컴포지션 API는 더 유연하고 재사용 가능한 컴포넌트를 만들 수 있게 합니다.

 

예제:

<template>
  <div>{{ count }}</div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const count = ref(0);

    onMounted(() => {
      console.log('Component Mounted');
    });

    return {
      count
    };
  }
}
</script>

 

7. 결론

Vue.js 컴포넌트는 강력한 기능을 제공하여 복잡한 애플리케이션을 모듈화하고 관리하기 쉽게 만듭니다. 컴포넌트의 개념과 활용 방법을 잘 이해하면 Vue.js 애플리케이션을 더 효율적으로 개발할 수 있습니다.

slot

Vue.js에서 slot은 부모 컴포넌트에서 자식 컴포넌트로 콘텐츠를 전달하기 위한 메커니즘입니다. 이를 통해 자식 컴포넌트의 특정 위치에 부모 컴포넌트가 제공하는 내용을 삽입할 수 있습니다. slot은 기본적으로 재사용 가능한 컴포넌트를 작성할 때 유용합니다.

기본 슬롯

기본 슬롯은 자식 컴포넌트의 <slot> 태그로 정의됩니다. 부모 컴포넌트는 이 슬롯에 내용을 삽입할 수 있습니다.

자식 컴포넌트 (ChildComponent.vue):

<template>
  <div class="child">
    <slot></slot>
  </div>
</template>

 

부모 컴포넌트 (ParentComponent.vue):

<template>
  <div class="parent">
    <child-component>
      <p>This content is passed to the child component's slot.</p>
    </child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  }
}
</script>

이 예제에서 부모 컴포넌트의 <p> 태그는 자식 컴포넌트의 <slot> 태그 위치에 삽입됩니다.

명명된 슬롯

여러 개의 슬롯이 필요한 경우 name 속성을 사용하여 명명된 슬롯을 정의할 수 있습니다.

자식 컴포넌트 (ChildComponent.vue):

<template>
  <div class="child">
    <slot name="header"></slot>
    <slot></slot> <!-- 기본 슬롯 -->
    <slot name="footer"></slot>
  </div>
</template>

 

부모 컴포넌트 (ParentComponent.vue):

<template>
  <div class="parent">
    <child-component>
      <template v-slot:header>
        <h1>This is the header</h1>
      </template>

      <p>This content is passed to the default slot.</p>

      <template v-slot:footer>
        <footer>This is the footer</footer>
      </template>
    </child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  }
}
</script>

이 예제에서 부모 컴포넌트는 header, default, footer 세 개의 슬롯에 각각 콘텐츠를 전달합니다.

스코프 슬롯

스코프 슬롯은 자식 컴포넌트가 부모 컴포넌트에 데이터를 전달할 수 있도록 합니다. 이는 주로 자식 컴포넌트 내부의 상태나 데이터를 부모 컴포넌트에서 사용할 수 있도록 할 때 유용합니다.

자식 컴포넌트 (ChildComponent.vue):

<template>
  <div class="child">
    <slot :message="message"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello from child'
    }
  }
}
</script>

 

부모 컴포넌트 (ParentComponent.vue):

<template>
  <div class="parent">
    <child-component>
      <template v-slot:default="slotProps">
        <p>{{ slotProps.message }}</p>
      </template>
    </child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  }
}
</script>

 

이 예제에서 자식 컴포넌트는 message 데이터를 슬롯에 전달하고, 부모 컴포넌트는 이를 slotProps를 통해 받아서 사용합니다.

이와 같이 Vue.js의 slot은 컴포넌트 간의 유연한 콘텐츠 전달을 가능하게 하여 재사용성과 유지보수성을 높입니다.

반응형