| ์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
- ์ฝํ๋ฆฐ ์๊ณ ๋ฆฌ์ฆ
- kotlin ์๊ณ ๋ฆฌ์ฆ
- javascript
- ์๊ณ ๋ฆฌ์ฆ
- Vue.js
- js
- ํ์ฝํ
- Swift
- ์๋ฐ
- ๋ฐฑ์ค ์ฝํ๋ฆฐ
- ๋ฏธ๊ตญ์ฃผ์
- GIT
- ์๋ฐ ์๊ณ ๋ฆฌ์ฆ
- vue3
- pnpm
- linux
- ์๋ฐ์คํฌ๋ฆฝํธ
- CI/CD
- ๋ฐฑ์ค
- Kotlin
- ์ฝํ๋ฆฐ ์คํ
- ํ๋ก๊ทธ๋๋จธ์ค
- ๋ฐฐ๋น์ฃผ
- ๋ฏธ๊ตญ๋ฐฐ๋น์ฃผํฌ์
- ํ์ด์ฌ
- Java
- java ์ฝ๋ฉ ํ ์คํธ
- python
- kotlin algorithm
- ์ฝํ๋ฆฐ
- Today
- Total
๐ ์ ์ด์ ๋จธ๋ฆฟ์์ผ๋ก
[Vue .js] Composition API : props, emits ์ฌ์ฉ๋ฒ ๋ณธ๋ฌธ
composition API porps, emits ์ฌ์ฉ๋ฒ
Vue์ ์ถ๊ฐ๋ composition API๋ Vue2์์์ option API๋ณด๋ค ์ปดํฌ๋ํธ๋ฅผ ์กฐ๊ธ ๋ ๋ ๋ฆฝ์ ์ผ๋ก ๋ง๋ค๊ธฐ ์ ๋ฆฌํ๋ค.
๊ด์ฌ์ฌ์ ๋ถ๋ฆฌ(์์ ์ปดํฌ๋ํธ๋ ๋ฐ์ดํฐ ์ปจํ ์ด๋ ์ญํ ๋ก ๋ฐ์ดํฐ๋ฅผ ์ง์ ์กฐ์, ํ์ ์ปดํฌ๋ํธ๋ ๋ฐ์ดํฐ๋ฅผ ์กฐ์ํ์ง ์๊ณ ํํ๋ง์ ๋ด๋น)๋ฅผ ํตํด ์ปดํฌ๋ํธ์ ์ฌ์ฌ์ฉ๋ฅ ์ ๋์ผ ์ ์๋ค.
props์ emits ์ฌ์ฉ๋ฒ ์์
์๋์์๋ App.vue ์์์ TodoList.vue ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด๋ค.
App.vue
<template>
<div id="app">
<TodoList :todoItemProps="todoItems" @emitClickList="alertList"></TodoList>
</div>
</template>
<script setup>
import TodoList from './components/TodoList.vue'
import { ref } from 'vue';
const todoItems = ref(['itemOne', 'itemTwo', 'itemThree']);
const alertList = (idx) => {
alert(todoItems.value[idx]);
}
</script>
์์ ์ปดํฌ๋ํธ์ธ App.vue์์ ํ์ ์ปดํฌ๋ํธ์๊ฒ datadls props๋ฅผ ๋ด๋ ค์ฃผ๊ณ ํ์ ์ปดํฌ๋ํธ์๊ฒ ์ด๋ฒคํธ์ธ emits์ ๋ฐ๋๋ค.
ํ์์ปดํฌ๋ํธ(TodoList.vue)์ todoItemsProps๋ ์ด๋ฆ์ props์ ์์์ปดํฌ๋ํธ(App.vue)์ todoItems๋ผ๋ ๋ฐฐ์ด์ ๋ด๋ฆฐ๋ค.
ํ์์ปดํฌ๋ํธ(TodoList.vue)์ emitClickList๋ ์ด๋ฆ์ ์ด๋ฒคํธ์ ์์์ปดํฌ๋ํธ(App.vue)์ alertList ๋ผ๋ ํจ์๋ฅผ ์คํํ๋ค.
TodoList.vue
<template>
<div>
<ul>
<li v-for="(todoItem, idx) in props.todoItemProps" v-bind:key="todoItem">
<span>{{ todoItem.item }}</span>
<span @click="clickList(idx)">Alert</span>
</li>
</ul>
</div>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
//์์ ์ปดํฌ๋ํธ์์ todoItemsProps๋ผ๋ ์ด๋ฆ์ props๋ฅผ ์ ์ธ(type์ ๋ฐฐ์ด)
//type => ๋ฌธ์์ด: String, ์ซ์ํ: Number, ๋ฐฐ์ด: Array, ๋
ผ๋ฆฌํ: Boolean
todoItemProps: Array
})
const emit = defineEmits(['emitClickList'])
const clickList = (idx) => {
//idx ์ธ์๋ฅผ emitClickList ๋ผ๋ ์ด๋ฆ์ผ๋ก ์์ ์ปดํฌ๋ํธ์ ์ ๋ฌ
emit('emitClickList', idx);
}
</script>
1. props, emit์ ๋ชจ๋ ๊ฐ์ฒด๋ก defineProps, defineEmits ํจ์๋ฅผ ์ด์ฉํ์ฌ ์ ์ธ ๋ฐ ์ ์ํ๋ค.
2. props์๋ ์์ ์ปดํฌ๋ํธ์์ ๋ฐ์ ๋ฐ์ดํฐ ํ์ ์ ์ ์ํ๋ค.
3. emit์๋ ์์ ์ปดํฌ๋ํธ์ ๋๊ฒจ์ค emit๋ค์ ๋ฐฐ์ด๋ก ์ ์ธํ๋ค.
todoItemProps ์์๋ ์์ ์ปดํฌ๋ํธ์์ ๋๊ฒจ์ค todoItems ๋ผ๋ ๋ฐฐ์ด์ด ๋ค์ด์๋ค.
๋ฐฐ์ด์ ๊บผ๋ด์ธ ๋๋ in ํํ์์ ์ด์ฉํด์ ๋ฐฐ์ด ์์ ๋ฐ์ดํฐ์ ์ ๊ทผํ ์ ์๋ค. (์์ดํ , ์ธ๋ฑ์ค) in ๋ฐฐ์ด๊ฐ
์์ดํ , ์ธ๋ฑ์ค ์์๋ก ์ ๊ณต๋๊ณ ์ด๋ฆ์ ์์๋ก ์ ํ ์ ์๋ค.
@click์ ํตํด์ ํด๋ฆญ ์ด๋ฒคํธ๊ฐ ์ผ์ด๋ฌ์๋ clickList ํจ์๊ฐ ์คํ๋๊ณ ํด๋น ํจ์๋ emitClickList๋ผ๋ ์ด๋ฆ์ผ๋ก ์ธ์์ธ idx๋ฅผ ์์ ์ปดํฌ๋ํธ์ ์ฌ๋ ค์ค๋ค.
์์ ์ปดํฌ๋ํธ์์ ํด๋น emit์ด ์ผ์ด๋ฌ์ ๋, ์ํ๋ ํจ์๋ฅผ ์ ์ํ๋ค.