Today I Learned 48 - Vue / SFC

angie·2022년 11월 3일

Vue.js

목록 보기
6/12
post-thumbnail

1. component

  • UI를 독립적으로 재사용 가능한 조각들로 나눈 것
  • 하나의 앱을 구성할 때 중첩된 컴포넌트들의 트리로 구성하는 것이 보편적이다.
  • 컴포넌트는 유지보수와 재사용성 측면에서 좋다.

component 이름 표기법

  • 컴포넌트 이름은 그 컴포넌트를 어디에 쓸 지에 따라 달라진다.

kebab-case

Vue.component('my-component-name', { /* ... */ })
  • 케밥-표기법으로 컴포넌트 정의 시 사용할 때도 <my-component-name>와 같이 케밥-표기법으로 사용해야 한다.

PascalCase

Vue.component('MyComponentName', { /* ... */ })
  • 파스칼표기법으로 컴포넌트 정의 시 사용할 때 두 가지 표기법 모두 사용할 수 있다.
  • <my-component-name>, <MyComponentName> 모두 가능
  • 단, DOM에 쓸 때는 케밥-표기법만 가능

2. SFC

component in Vue

  • Vue에서 component = new Vue()로 만든 Vue 인스턴스

SFC (Single File Component)

  • 하나의 .vue 파일이 하나의 Vue instance이고, 하나의 컴포넌트이다.

3. Vue Component

1) Vue component의 구조

.vue 파일은 아래와 같은 기본 구성으로 이루어져 있다.

<template> // html 
</template>

<script>   // script
export default {};
</script>

<style>    // style
</style>

.vue 파일은 자신만의 html, style, script를 가지기 때문에, 컴포넌트 별로 독립된 환경을 가지고 개발할 수 있다.

template

  • html의 body 부분
  • 눈으로 보여지는 요소 작성
  • 다른 컴포넌트를 HTML 요소처럼 추가 가능

script

  • 자바스크립트 코드 작성
  • 각 컴포넌트의 정보, 데이터, 메서드 등 Vue instance를 구성하는 대부분이 작성됨

style

  • CSS가 작성되며 컴포넌트 스타일을 담당

2) component 사용하기

step1. 컴포넌트 만들기

새로운 .vue 파일 생성

  • 새로운 component를 src/components/ 안에 생성
  • 컴포넌트 파일 이름은 대문자로 시작

script에 이름 등록

  • 새롭게 생성한 .vue파일에 script 부분에 이름을 등록한다.
<script>
  export default {
	name: 'MyComponent',
}
</script>

template에서 컴포넌트 추가

<template>
  	<div>
		<h1>컴포넌트</h1>
  	</div>
</template>
  • template안은 비어 있으면 안됨
  • 한 개 이상의 최상위 태그가 있어야함

step2. 컴포넌트 등록

불러오기

하위 컴포넌트를 사용할 상위 컴포넌트의 script 부분에 하위 컴포넌트를 불러온다.

// 문법
import {instance name} from {location}
  • instance name은 instance 생성시 작성한 'name'
  • @은 'src'의 shortcut (절대 경로)
  • .vue 확장자는 생략 가능

등록하기

상위 컴포넌트의 instance 객체의 components에 등록한다.

보여주기

상위 컴포넌트의 template 부분에서 등록한 컴포넌트를 사용한다.

// 예시
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <!-- 3. 보여주기 -->
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <MyComponent/>
  </div>
</template>

<script>
// 1. 불러오기
import HelloWorld from './components/HelloWorld.vue'
// @ : 절대경로 의미 (src), vue 확장자 생략
import MyComponent from '@/components/MyComponent'

export default {
  name: 'App',
  // 2. 등록하기
  components: {
    HelloWorld,
    MyComponent,
  }
}
</script>
profile
better than more

0개의 댓글