๐ฉ๐ปโ๐ผ "computed๋ watch ๋ ๋ค ๋ฐ์ํ์ด๋๊น ๋๊ฐ์ ๊ฑฐ ์๋์ผ?"
๐ผ๐ป "์๋"
๋ฐ์ํ getter
ํ ํ๋ฆฟ์ ๋จ์ํ๊ณ ์ ์ธ์ ์ด์ฌ์ผ ํจ!
ํ ํ๋ฆฟ ๋ด์ ํํ์์ ๋ฃ์ผ๋ฉด ํธ๋ฆฌํ์ง๋ง, ๋๋ฌด ๋ง์ ์ฐ์ฐ์ ํ ํ๋ฆฟ์ ๋ณต์กํ๊ณ ์ ์ง ๋ณด์๊ฐ ์ด๋ ต๊ฒ ๋ง๋ฆ
author
๊ฐ ์ฑ
์ ๋๋์ง ์๋๋์ง์ ๋ฐ๋ผ ์ฒดํฌ๋ฅผ ํ๊ณ ์ถ๋ค๋ฉด ์๋์ ๊ฐ์ด ๋ํ๋ผ ์ ์์<div id="computed-basics">
<p>์ถํ๋ ์ฑ
:</p>
<span>{{ author.books.length > 0 ? '์์' : '์์' }}</span>
</div>
Vue.createApp({
data() {
return {
author: {
name: '์กด ๋์ฐ',
books: [
'Vue 2 - Advanced Guide',
'Vue 3 - Basic Guide',
'Vue 4 - The Mystery'
]
}
}
}
})
<span>
ํ๊ทธ ๋ด์ ํํ์์ ๋ฃ์ผ๋ฉด์ ์ง์ ๋ถํด์ง<div id="computed-basics">
<p>์ถํ๋ ์ฑ
:</p>
<span>{{ publishedBooksMessage }}</span>
</div>
Vue.createApp({
data() {
return {
author: {
name: '์กด ๋์ฐ',
books: [
'Vue 2 - Advanced Guide',
'Vue 3 - Basic Guide',
'Vue 4 - The Mystery'
]
}
}
},
computed: {
publishedBooksMessage() {
// ์ฌ๊ธฐ์์ `this` ๋ vm ์ธ์คํด์ค์ด๋ค.
return this.author.books.length > 0 ? '์์' : '์์'
}
}
}).mount('#computed-basics')
publishedBooksMessage
๋ author.books
์ ์์กดํจ.Computed์ ๋ฉ์๋ ์ฐจ์ด
๐ฉ๐ปโ๐ผ "๊ทธ๋ฅ ๋ฉ์๋์ ๋๊ฐ์ด publishedBooksMessage() ๋ง๋ค๋ฉด ๋๋๊ฑฐ ์๋ ?"
๐ผ "๊ฒฐ๊ณผ๋ ๊ฐ์ง๋ง~~ ๋ด๋ถ์ ์ผ๋ก computed๊ฐ ๋ ์ข์~~ "
- author.books๊ฐ ๋ณ๊ฒฝ๋์ง ์๋๋ค๋ฉด, computed ์์ฑ์ ๋ํด ์ฌ๋ฌ๋ฒ ์ ๊ทผํ๋๋ผ๋
ํจ์๋ฅผ ๋ค์ ์คํํ ํ์ ์์ด ์ด์ ์ ๊ณ์ฐ๋ ๊ฒฐ๊ณผ๋ฅผ ์ฆ์ ๋ฐํํจ!- ํ์ง๋ง ๋ฉ์๋์ ์ ์ธํ ํจ์๋ ์ฌ๋ ๋๋ง์ด ๋ฐ์ํ ๋๋ง๋ค ํญ์ ํจ์๋ฅผ ์คํํ๊ฒ ๋จ
set
computed: {
fullName: {
get() {
return this.firstName + ' ' + this.lastName
},
set(newValue) {
const names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
๋ฐ์ํ ์ฝ๋ฐฑ
์ธ์คํด์ค์ ํน์ ๋ฐ์ดํฐ๊ฐ ๋ณ๊ฒฝ๋ ๋ ์ง์ ํ ์ฝ๋ฐฑํจ์๊ฐ ์คํ๋จ
์ฃผ๋ก computed ์์ฑ์ด ๋ ๋ง์ด ์ฌ์ฉ๋์ง๋ง, watch๊ฐ ํ์ํ ๊ฒฝ์ฐ๊ฐ ์์
<div id="watch-example">
<p>
์/์๋์ค ์ง๋ฌธ์ ๋ฌผ์ด๋ณด์ธ์.
<input v-model="question" />
</p>
<p>{{ answer }}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script>
const watchExampleVM = Vue.createApp({
data() {
return {
question: '',
answer: '์ง๋ฌธ์ ๋ณดํต ๋ฌผ์ํ๋ฅผ ํฌํฉํฉ๋๋ค. ;-)'
}
},
watch: {
// question ์ด ๋ณ๊ฒฝ๋ ๋๋ง๋ค, ์ด ํจ์๊ฐ ์คํ๋ ๊ฒ ์
๋๋ค.
question(newQuestion, oldQuestion) {
if (newQuestion.indexOf('?') > -1) {
this.getAnswer()
}
}
},
methods: {
getAnswer() {
this.answer = '์๊ฐ์ค...'
axios
.get('https://yesno.wtf/api')
.then(response => {
this.answer = response.data.answer
})
.catch(error => {
this.answer = '์๋ฌ! API์ ๋ฟ์ง ๋ชปํ์ต๋๋ค. ' + error
})
}
}
}).mount('#watch-example')
</script>
data์ ํ ๋น๋ ๊ฐ ์ฌ์ด์ ์ข
์๊ด๊ณ๋ฅผ ์๋์ผ๋ก ์ธํ
ํ๋ ค๋ฉด computed
computed
์?
๐คํน์ ๋ฐ์ดํฐ์ ๋ณ๊ฒฝ ์์ ์ ํน์ ์ก์
(call api, push route ...) ์ ์ทจํ๊ณ ์ ํ ๋ watch
๐ Computed ์์ฑ vs Watch ์์ฑ
๐ watch์ computed ์ ์ฐจ์ด์ ์ฌ์ฉ๋ฒ