โ Composition API๋?
setup() ํจ์ ์์์ ref, reactive, computed, watch ๋ฑ์ ํ์ฉํ์ฌ ์ปดํฌ๋ํธ ๋ก์ง์ ๊ตฌ์ฑํ๋ ๋ฐฉ์
App.vue
<script setup>
import { ref , onMounted, watch} from 'vue';
import ChildComp from './components/ChildComp.vue';
let count = ref(0); // ์ํ๋ณ์ ์ด๊ธฐ๊ฐ(state), import ref ํ์
let title = "Hello Vue";
let color = ref('green');
onMounted(() => {
console.log('mounted'); // import onMounted ํ์
})
const increaseCount = () => {
count.value++; // let count์ count๋ ref์ ์๊ธฐ ๋๋ฌธ์ .valueํ์
}
watch(color, () => { // import watch ํ์
console.log('color ๋ณ๊ฒฝ');
})
</script>
<template>
<div>
<h1>{{title}}</h1>
<button @click="increaseCount">count++</button>
<p>{{ count }}</p>
<ChildComp :color="color" bgColor="yellow" />
<button @click="color='red'">change color</button>
</div>
</template>
<style scoped>
</style>
- ref๋ก ์ํ๋ณ์ ์ด๊ธฐ๊ฐ ์ค์
- ๊ฐ์ .value๋ก ๊บผ๋ด์ผ ํ๋ค.
- ๋ผ์ดํ์ฌ์ดํด ํ ์ ํ์ฉํ๋ ค๋ฉด import onMounted, watch ํ์
- ํจ์ ์ ์๋ script์์ ๋ฐ๋ก ํ๋ฉด ๋๋ค.
ChildComp.vue
<template>
<div>
<h2>Child Component</h2>
<p
:style="{
color: color,
backgroundColor: bgColor
}"
>{{ color }}</p>
</div>
</template>
<script setup>
// export default ํ์ ์์ด ๋ณ์๋ก props ๋ฑ๋ก
const props = defineProps ({
color: String, // ์๋ฃํ ์ ๋ ๊ฒ์ ๋์ผ์ผ
bgColor: String,
})
console.log(props.color);
</script>
<style>
</style>
- script์์ export default ํ์ ์์ด ๋ฐ๋ก props ๋ฑ๋ก ๊ฐ๋ฅ
๐ Options API vs Composition API
ํญ๋ชฉ | Options API | Composition API |
Vue 2 ๋ฐฉ์ | data() , methods , computed ๋ฑ ์ต์
์ผ๋ก ๊ตฌ์ฑ | setup() ๋ด๋ถ์์ ๋ก์ง ์์ฑ |
๊ตฌ์กฐ | ๊ธฐ๋ฅ์ด ์์ฌ ์์ | ๊ธฐ๋ฅ๋ณ๋ก ๋ชจ์์ ์์ฑ |
์ฝ๋ ์ฌ์ฌ์ฉ | ๋ฏน์ค์ธ, HOC ๋ฑ (ํ๊ณ ์์) | ๋ก์ง์ ํจ์๋ก ๋ถ๋ฆฌ ( useXXX() ) |
๊ถ์ฅ ์์ | ๊ฐ๋จํ ์ปดํฌ๋ํธ | ๋ณต์กํ ์ปดํฌ๋ํธ, ์ฌ์ฌ์ฉ ๋ง์ ๊ฒฝ์ฐ |
๐ฆ ์ฃผ์ API ์ ๋ฆฌ
API | ์ค๋ช
| ์์ |
ref() | ์์๊ฐ ๋ฐ์ํ ์ํ | const msg = ref("hi") |
reactive() | ๊ฐ์ฒด ์ ์ฒด๋ฅผ ๋ฐ์ํ์ผ๋ก | const user = reactive({ name: "Lee" }) |
computed() | ๊ณ์ฐ๋ ์์ฑ | const double = computed(() => count.value * 2) |
watch() | ๊ฐ ๋ณํ ๊ฐ์ง | watch(count, (newVal) => console.log(newVal)) |
onMounted() | ์๋ช
์ฃผ๊ธฐ ํ
| onMounted(() => { ... }) |
โ ์ฅ์
- ์ฝ๋ ์์ง๋ ฅ ํฅ์: ๊ด๋ จ๋ ๋ก์ง์ ํ ๊ณณ์ ๋ชจ์ ์ ์์
- ์ฌ์ฌ์ฉ ์ฌ์:
useXXX
ํจ์๋ก ์ถ์ถ ๊ฐ๋ฅ
- ํ์ ์คํฌ๋ฆฝํธ์ ์ ๋ง์: ๋ช ์์ ์ด๊ณ ํจ์ ์ค์ฌ ๊ตฌ์กฐ
๐ ์ธ์ ์ฐ๋ฉด ์ข์๊น?
- ๋ก์ง์ด ๋ณต์กํ๊ฑฐ๋ ๊ธฐ๋ฅ๋ณ ๋ถ๋ฆฌ๊ฐ ํ์ํ ๊ฒฝ์ฐ
- ์ฌ๋ฌ ์ปดํฌ๋ํธ์์ ๊ฐ์ ๋ก์ง์ ๊ณต์ ํด์ผ ํ๋ ๊ฒฝ์ฐ
- ํ์ ์คํฌ๋ฆฝํธ๋ฅผ ์ ๊ทน ํ์ฉํ๋ ํ๋ก์ ํธ
Share article