Input + Output = True
vue 3 ๋ฐ์ํ - reactive and ref ๋ณธ๋ฌธ
๐ vue 3 ๋ฐ์ํ - reactive and ref
composition API๋ฅผ ๊ธฐ์ค์ผ๋ก ํฉ๋๋ค
๋ฐ์ํ
vue์์๋ ๋ฐ์ดํฐ์ ์ค์๊ฐ ์ ๋ฐ์ดํธ๊ฐ ๊ฐ๋ฅํ ๊ฒ์ ๋ฐ์ํ์ด๋ผ๊ณ ํ๋ค
โ reactive
reactive() ํจ์๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ์ฒด ๋๋ ๋ฐฐ์ด์ ๋ฐ์ํ์ผ๋ก ๋ง๋ค ์ ์๋ค
๋ฐํ ๊ฐ์ ์๋ณธ ๊ฐ์ฒด์ ๊ฐ์ง ์๊ณ ์๋ณธ ๊ฐ์ฒด๋ฅผ ์ฌ์ ์ํ ๊ฐ์ฒด์ด๋ค
const raw = {}
const proxy = reactive(raw)
// ๋ฐ์ํ์ผ๋ก ์ฌ์ ์ ๋ ๊ฒ์ ์๋ณธ๊ณผ ๊ฐ์ง ์๋ค
console.log(proxy === raw) // false
๊ฐ์ฒด, ๋ฐฐ์ด ๋๋ Map์ด๋ Set๊ณผ ๊ฐ์ ์ปฌ๋ ์ ์ ํ์๋ง ์ฌ์ฉ ๊ฐ๋ฅํ๋ค
reactive ์์
์ซ์๊ฐ ์ฆ๊ฐํ๋ฉฐ ํ๋ฉด์ ์ค์๊ฐ ๋ฐ์ธ๋ฉ์ ํ๋ ์์ ์ด๋ค
reactive ์ฌ์ฉ ์ฌ๋ถ์ ๋ฐ๋ฅธ ์ฐจ์ด์ ์ ๋น๊ตํด๋ณด์
<div>{{ state.count }}</div>
<button @click="state.count++">state.count++</button>
<div>{{ countNormal }}</div>
<button @click="countNormal++">countNormal++</button>
import { reactive } from "vue"
const countNormal = 0
const state = reactive({ count: 0 })
reactive๋ฅผ ์ฌ์ฉํ state.count์ ์ค์๊ฐ ๋ฐ์ธ๋ฉ๋ง ๊ฐ๋ฅํ๋ค
์ด๋ ๊ฒ ์ค์๊ฐ ๋ฐ์ธ๋ฉ์ด ๊ฐ๋ฅํ ๊ฒ์ vue์์๋ ๋ฐ์ํ์ด๋ผ๊ณ ํ๋ค
reactive()๋ ์์ ๋ฅผ ๋ณด๋ฉด ์ ์ ์๋ฏ์ด state.count์ฒ๋ผ ํน์ ๊ฐ์ ์ ๊ทผํ ๋์๋ ๋ฐ์ดํฐ์ ์์ฑ์ผ๋ก ์ ๊ทผํด์ผํ๋ค
โ ref
ref()๋ reactive์ ์ ํ ์ฌํญ์ ํด๊ฒฐํ๊ธฐ ์ํด, ํ์ ์ ํ ์์ด ๋ฐ์ดํฐ๋ฅผ ๋ฐ์ํ์ผ๋ก ์ฌ์ ์ํ ์ ์๋ ํจ์์ด๋ฉฐ
.value ์์ฑ์ ํฌํจํ๋ ref ๊ฐ์ฒด๋ก ๋ฐํํ๋ค
const countRef = ref(0)
console.log(countRef) // { value: 0 }
console.log(countRef.value) // 0
countRef.value++
console.log(countRef.value) // 1
ref ์์
reactive() ์์ ์ ๊ฐ์ด '์ซ์๊ฐ ์ฆ๊ฐํ๋ฉฐ ํ๋ฉด์ ์ค์๊ฐ ๋ฐ์ธ๋ฉ์ ํ๋ ์์ '๋ฅผ ํตํด์
reactive์ ref์ ๋ฌธ๋ฒ ์ฐจ์ด์ ์ ๋น๊ตํด๋ณด์
<div>{{ stateReactive.count }}</div>
<button @click="stateReactive.count++">stateReactive.count++</button>
<div>{{ countRef }}</div>
<button @click="countRef++">countRef++</button>
import { reactive, ref } from "vue"
const stateReactive = reactive({ count: 0 })
console.log(stateReactive.count)
const countRef = ref(0)
console.log(countRef.value)
template์ ๋ฐ์ธ๋ฉ์ ํ ๋ ref๋ ์์ฑ์ด ์๋ ํด๋น ๋ฐ์ดํฐ์ ๋ฐ๋ก ์ ๊ทผํ ์ ์๊ธฐ ๋๋ฌธ์ reactive์ ๋นํด ๊ฐ๋จํ๋ค
ํ์ง๋ง ref๋ script ์์ญ์์ ํด๋น ๋ฐ์ดํฐ์ ์ ๊ทผํ๊ธฐ ์ํด์๋ .value๋ฅผ ํตํด์ ์ ๊ทผํด์ผ ํ๋ค
โ reactive vs ref
- reactive()์ ref() ๋ชจ๋ ์๋ก์ด ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ค
- reactive๋ ๊ฐ์ฒด์ ๋ฐฐ์ด ๋๋ ์ปฌ๋ ์ ์ ํ๋ง ๋ฐ์ํ์ผ๋ก ์ฌ์ ์ํ ์ ์๋ค
- ref๋ ํ์ ์ ํ ์์ด ์ฌ์ฉ ๊ฐ๋ฅํ๋ค
reactive์ ref๋ฅผ ํผ์ฉํ ์ง ํ๋๋ง์ ์ฌ์ฉํ ์ง์ ๋ํ ์ปจ๋ฒค์ ์ ์ ์ํ ํ ํด๋น ์ปจ๋ฒค์ ์ ๋ฐ๋ผ๊ฐ๋ฉด ๋๋ค
โ ๋ํ, ์ธ๋ํ
์ด๋ค ๊ฐ์ด ref์ ํ ๋น๋์ด ์๋ค๊ณ ๊ฐ์ ํ๋ค
์๋ ์์ ๋ฅผ ๋ณด๋ฉด script ์์ญ์์๋ ๋ํ๋์ด ์๊ณ template ์์ญ์์๋ ์ธ๋ํ๋์ด ์๋ค
<div>{{ countRef }}</div>
<button @click="countRef++">countRef++</button>
import { ref } from "vue"
const countRef = ref(0)
console.log(countRef.value)
https://v3-docs.vuejs-korea.org/guide/essentials/reactivity-fundamentals.html
๋ฐ์ํ ๊ธฐ์ด | Vue.js
v3-docs.vuejs-korea.org
'๐จFrontEnd > Vue' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
vue 3 - v-for ๋ฐ๋ณต๋ฌธ (0) | 2023.07.12 |
---|---|
vue 3 - v-if, v-show (0) | 2023.07.12 |
vue 3 - class & style (0) | 2023.07.11 |
vue 3 - computed (computed vs method) (0) | 2023.07.09 |
vue 3 ๊ธฐ๋ณธ ๋ฌธ๋ฒ (1) | 2023.07.04 |