했던것들/Vue.JS

Vue.JS) 공식문서 Introduction 일부 발췌 번역

2DC 2023. 1. 21. 12:51

What is Vue? (Vue는 무엇인가요?)

Vue(발음은 view, 뷰로 하면 된다.)는 UI를 개발하는 자바스크립트 프레임워크이다.

뷰는 표준 HTML, CSS, JS를 기반으로 빌드(구축)되며, UI를 효율적으로 개발할 수 있도록 도와주는 선언형 프로그래밍(declarative)컴포넌트 기반 프로그래밍 모델을 제공한다.

 

아래는 미니멀한 예시이다.

import { createApp } from 'vue';

createApp({
  data() {
    return {
      count: 0;
    }
  }
}).mount('#app')
<div id="app">
  <button @click="count++">
    Count is: {{ count }}
  </button>
</div>

결과 :

위의 예시는 뷰의 두 가지 핵심 기능을 보여준다.

  • Declarative Rendering (선언적 렌더링)
    - Vue extends standard HTML with a template syntax that allows us to declaratively describe HTML output based on JavaScropt state
    (번역해놓으면 뜻 전달이 잘 안됨. 대충 JS의 state 변경이 HTML에 잘 연동이 되어 액션에 따라 변하는 state를 화면에 잘 렌더링할 수 있다는 뜻임)
  • Reactivity
    -  뷰는 자바스크립트의 state의 변경을 자동으로 추적하며, 변경될 때마다 DOM을 효율적으로 업데이트함.

The Progressive Framework (진보적 프레임워크)

뷰는 프론트엔드 개발에 필요한 공통적인 기능을 커버하는 프레임워크이자 에코시스템이다.

하지만 웹은 극도로 광범위하다. - 즉 우리가 웹에 구축하는 것들은 형태와 규모 면에서 급격하게 달라질 수 있다.

이러한 점을 바탕으로, 뷰는 유연하고 adoptable하게 디자인되었다. 

use case에 따라 뷰는 각자 다른 방법으로 사용될 수 있다.

  • Enhancing static HTML without a build step (빌드 스텝 없이 정적 HTML 향상 (?))
  • Embedding as Web Components on any page
  • Single-Page Application (SPA)
  • Fullstack / Server-Side Rendering (SSR)
  • Jamstack / Static Site Generation (SSG)
  • Targeting desktop, mobile, WebGL, and even the terminal

Single-File Components (SFC)

대부분의 뷰 프로젝트에서, 우리는 Single-File Component라는 HTML과 비슷한 파일 포맷을 사용하여 뷰 컴포넌트를 작성한다. (*.vue 파일이라고도 하며, 약어는 SFC이다)

SFC는 이름에서 나오는 대로, 하나의 파일에 JS 로직과 HTML 템플릿, CSS 스타일까지 전부 캡슐화해서 사용한다.

아래는 SFC 방식으로 써진 이전(앞서 나왔던) 예제이다.

<script>
export default {
  data() {
    return {
      count: 0
    }
  }
}
</script>

<template>
  <button @click="count++">Count is: {{ count }}</button>
</template>

<style scoped>
button {
  font-weight: bold;
}
</style>

API Style

뷰 컴포넌트는 두가지 다른 API 스타일로 작성할 수 있다. (Options API & Composition API)

 

Options API

Options API는 data, methods, mounted 와 같은 옵션 객체를 이용하여 컴포넌트 로직을 정의하는 것을 말한다.

옵션으로 정의된 프로퍼티는 this로 노출이 되며, this는 내부 함수의 컴포넌트 인스턴스를 가리킨다.

<script>
export default {
  // Properties returned from data() become reactive state and will be exposed on `this`
  // data()에서 return된 프로퍼티는 활성(reactive) 상태가 되고, `this`에 의해 노출됨.
  data() {
    return {
      count: 0
    }
  },
  
  // Methods are functions that mutate state and trigger updates.
  // They can be bound as event listeners in templates.
  // Methods는 state를 변경하고, 업데이트의 트리거 역할을 하는 함수이다.
  // 템플릿에서 '이벤트 리스너'로 바운드할 수 있다.
  methods: {
    increment() {
      this.count++
    }
  },
  
  // Lifecycle hooks are called at different stages of a component's lifecycle.
  // This function will be called when the component is mounted.
  // lifecycle hooks은 컴포넌트의 생애주기의 다양한 단계에서 호출되며,
  // 이 함수는 컴포넌트가 마운트된 상태일 때 호출된다.
  mounted() {
    console.log(`카운트 값은 ${this.count} 입니다.`)
  }
}
</script>
<template>
  <button @click="increment">Count is: {{ count }}</button>
</template>

 

Composition API

Composition API는 import한 API function을 이용하여 내부 로직을 정의한다.

SFC에서 Composition API는 보통 <script setup> 와 함께 사용된다.

 

setup 어트리뷰트는 뷰가 컴파일을 하는 것을 효율적으로 해줄 수 있도록 하는 하나의 힌트 역할을 한다.

예를 들자면,

<script setup> 내부에 선언된 import문과 top-level 변수 / 함수들은 템플릿에서 직접 사용할 수 있게 된다.

 

아래는 완전히 위와 동일한 예제를 Composition API를 통해 구현한 것이다.

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

// reactive state
const count = ref(0);

// state를 변경하고 업데이트 트리거 역할을 하는 함수
function increment() {
  count.value++
}

// lifecycle hooks
onMounted(() => {
  console.log(`카운트 값은 ${this.count} 입니다.`)
})
</script>

<template>
  <button @click="increment">Count is: {{ count }}</button>
</template>