Computed ์ฌ์ฉ๋ฒ
<template>
<h1> Full Name : {{ fullName }} </h1>
</template>
<script>
export default {
data() {
return {
firstName: 'SungJae',
lastName: 'Park'
}
},
computed: {
fullName() {
return this.firstName + '' + this.lastName;
}
}
}
</script>
Computed ๋ด์ fullName์ด ์ ์๋์ด ์๊ณ , firstName๊ณผ lastName์ ํฉ์ณ์ ๋ฐํํด์ฃผ๋ ํจ์๋ก ์ ์๋์ด ์๋ค. ์ฌ๊ธฐ์ ํจ์ ๋ช ์ธ fullName์ ํจ์์ด์ ๋์์, Vue ์ธ์คํด์ค ๋ฐ์ดํฐ ํค ๊ฐ์ด๋ค. firstName, lastName์ Vue ์ธ์คํด์ค์ ๋ฐ์ดํฐ ๊ฐ์ผ๋ก ์ฌ์ฉํ๋ ๊ฒ๊ณผ ๋์ผํ ๋ฐ์ดํฐ ๊ฐ์ผ๋ก ์ ์ธ๋๋ ๊ฒ์ด๋ค.
Computed๋ ๋ฐ์ดํฐ ๊ฐ์ ๋ณ๊ฒฝ์ด ์ผ์ด๋๋์ง ๊ฐ์ํ๋ค๊ณ ํ๋ค. Computed๋ก ์ ์ํ๋ฉด fullName ํจ์๊ฐ ์คํ๋์ด ๋ฐ์ดํฐ fullName์ firstName๊ณผ lastName์ ํฉํ ๊ฐ์ด ํ ๋น๋๋ค.
firstName ํน์ lastName ๊ฐ ์ค ํ๋๋ผ๋ ๋ณ๊ฒฝ์ด ์ผ์ด๋๋ฉด fullName ํจ์๊ฐ ์๋์ผ๋ก ์คํ๋๊ณ , fullName ๊ฐ์ด ๊ฒฝ์ ๋๋ค. ์ ๋ฆฌํด๋ณด๋ฉด, computed์ ์ ์๋ fullName์ ํจ์์ด์ ๋์์ Vue ์ธ์คํด์ค์ ๋ฐ์ดํฐ์ด๋ค. computed์ ์ ์ํด์ ์ฌ์ฉํ๋ฉด ํ๋ฉด ๋ด ์ฌ๋ฌ ๊ณณ์์ fullName์ ์ฌ์ฉํ๋๋ผ๋ ์ด์ ๋ํ ์ฐ์ฐ์ ํ ๋ฒ ๋ฐ์ ์ผ์ด๋์ง ์๋๋ค.
โ Watch
<template>
<div>
<h1>FullName : {{ fullName }}</h1>
<button type="button" @click="changeName">๋ณ๊ฒฝ</button>
</div>
</template>
<script>
export default {
data() {
return {
firstName: "SungJae",
lastName: "Park",
fullName: "",
};
},
watch: {
firstName() {
this.fullName = this.firstName + "" + this.lastName;
},
lastName() {
this.fullName = this.firstName + "" + this.lastName;
},
},
methods: {
changeName() {
this.firstName = "SON7AE";
},
},
};
</script>
Watch ์ญ์ computed์ฒ๋ผ Vue ์ธ์คํด์ค์ ์ ์๋ ๋ฐ์ดํฐ ๊ฐ์ด ๋ณ๊ฒฝ์ด ์ผ์ด๋๋์ง๋ฅผ ๊ฐ์ํ๊ณ , ๋ณ๊ฒฝ์ด ์ผ์ด๋๋ฉด ์ง์ ๋ ํจ์๋ฅผ ์คํ์ํฌ ์ ์๋ค. ํ์ง๋ง computed์ ๊ฒฝ์ฐ๋ ๊ธฐ์กด์ ์ ์๋ ๋ฐ์ดํฐ ๊ฐ์ ๊ธฐ๋ฐ์ผ๋ก ์๋ก์ด ๋ฐ์ดํฐ ๊ฐ์ ํ์ฉํ๊ธฐ ์ํด ์ฌ์ฉ์ด ๋๋ค๋ฉด, Watch๋ Watch์ ์ ์๋ ๋ฐ์ดํฐ ๊ฐ ํ๋๋ง์ ๊ฐ์ํ๊ธฐ ์ํ ์ฉ๋๋ก ์ฌ์ฉ๋๋ค.
๋ํ Watch์ ๊ฒฝ์ฐ๋ computed์ ๋ค๋ฅด๊ฒ ์ค์ ๋ฐ์ดํฐ ๋ณ๊ฒฝ์ด ์ผ์ด๋๊ธฐ ์ ๊น์ง๋ ์คํ๋์ง ์๋๋ค.
์ฆ, ์ด๊ธฐ์ ์ง์ ๋ ๊ฐ์ธ firstName๊ณผ lastName์ ๊ฐ์ด ์์์๋ ๋ถ๊ตฌํ๊ณ , fullName์ ์ฌ์ ํ ์๋ฌด๋ฐ ๊ฐ๋ ํ ๋น๋์ง ์๋๋ค. firstName๊ณผ lastName์ ์ด๊ธฐ์ ํ ๋น๋ ๊ฐ์ด ๋ฐ๋์ ๋ณ๊ฒฝ๋์ด์ผ์ง๋ง, ๋ณ๊ฒฝ์ด ์ผ์ด๋์ผ๋ง watch๊ฐ ์คํ๋๋ค.