컴포지션 API를 사용하는 이유
<template>
<div>
<h1> {{ number }} </h1>
<button v-on:click="increase">상승</button>
<button v-on:click="decrease">하락</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
computed: {
number() {
return this.count + '입니다!'
},
},
methods: {
increase() {
++this.count
},
decrease() {
--this.count
}
}
}
</script>
<style>
#app {
text-align: center;
}
</style>
숫자를 증가시키는 코드를 옵션 API로 작성해보았습니다.
number()에 붙은 게 벌써 data, computed, methods 세 개입니다.
기능이 한 개라서 아직은 정리하는데 문제가 없지만
그런데 코드가 길어진다면? 어우; 코드 읽다가 오전근무 날리게 생겼어요.
옵션API와 컴포지션API의 전체적인 코드 비교
각 기능마다 색칠해놨는데 컴포지션API가 훨씬 직관적이고 깔끔해보입니다. 코드 수정할 때 편하겠네요!
컴포지션 API 참고 사이트
https://vuejs.org/guide/extras/composition-api-faq.html#more-flexible-code-organization
Composition API FAQ | Vue.js
vuejs.org
컴포지션 API 구현 따라하기
그럼 컴포지션 API를 어떻게 만드는지 볼까요?
<template>
<div>
<h1> {{ count +'입니다!' }} </h1>
<button v-on:click="increment">상승</button>
<button v-on:click="decreasement">하락</button>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
function decreasement() {
count.value--
}
onMounted(() => {
console.log(`The initial count is ${count.value}.`)
})
</script>
<style>
#app {
text-align: center;
}
</style>
참고 사이트