Component는 화면을 구성하는 하나의 조각 또는 하나의 요소입니다.
일반적으로 HTML을 구성할 때 우리는 header, footer, nav, content 등의 영역으로 구분지어 화면을 구성합니다. 이러한 요소들 하나 하나가 Component가 되게 됩니다.
vue-cli로 만들었던 프로젝트에는 components 폴더 하위의 HelloWorld.vue라는 파일이 있게 됩니다. 이러한 컴포넌트들을 여러개 생성하게 되는데 이를 위해 HelloWorld.vue를 삭제하겠습니다.
<template>
/* html */
</template>
<script>
export default {};
/* JavaScript */
</script>
<style>
/* CSS */
</style>
vue에서 Component들은 .vue라는 확장자를 갖고 위의 구성을 갖게 됩니다. 각 vue 파일들은 자신만의 html, css, script를 갖기 때문에 Component별로 독립적인 환경을 갖고 개발할 수 있습니다.
<style scoped>
h1 {
color: green;
}
</scoped>
위처럼 style태그에 scoped를 설정하게 되면 해당하는 vue 파일의 h1태그에서만 사용할 수 있다는 의미입니다.
<template>
</template>
<script>
export default {
name: Component명
}
</script>
<style scoped>
</style>
조각으로 분리한 Component들을 App.vue에서 조각을 조립합니다. 즉 App.vue는 다른 component들의 부모 component라고 할 수 있습니다.
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import Nav from "@/components/Nav";
import Content from "@/components/Content";
export default {
name: 'App',
components: {
Header,
Footer,
Nav,
Content
}
}
</script>
위의 코드를 보면 import문에 @가 붙은 것을 확인할 수 있습니다. @는 src까지의 절대 경로를 의미하며 @가 아닌 ./로 시작하는 상대 경로로도 사용할 수 있습니다.
ESLint는 문법적인 오류나 안티 패턴을 찾아주고 일관된 코드 스타일을 유지하게 하여 개발자가 쉽게 코드를 읽을 수 있도록 도와줍니다. ESLint는 하나의 단어로 된 component 이름을 차단하고 있습니다. 해당 에러명은 'multi-word-component-names'로 2개의 단어를 같이 사용해 만들어라 입니다.
해당 에러를 해결하기 위해 vue.config.js에 아래의 코드를 추가합니다.
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave:false
})
component에 style을 적용할 때는 앞에서 사용했던 대로 코드를 작성합니다.
<Header/>
<div class="wrap">
<Menu/>
<Content/>
</div>
<style scoped>
.wrap {
display: flex;
}
</style>
위와 같은 방식으로 사용할 수 있으며 component별로 html, script, style을 관리할 수 있기 때문에 관심사의 분리화, 모듈화가 용이해지는 장점이 있습니다.