Vue Computed/Watch
Computed
computed 를 통해 data 필드를 감지하고 새로운 필드를 정의해서 사용하는 법을 알아보자.
여기 data안에 firstName과 lsatName이 객체로 저장되어 있다.
data() {
return {
firstName: 'Jane',
lastName: 'Johnson',
};
},
이 두 객체를 한번에 렌더링 하고 싶으면 아래와 같이 적는 방법이 있다.
<template>
<div>
<h1>Hello {{ firstName }} {{ lastName }}</h1>
</div>
</template>
<script>
이런 방식도 유효하지만 여러번 작성해야 할 때 번거로울 수 있다.
우선 메소드를 이용하는 방식이있다. 메소드에 아래 처럼 작성한다.
methods: {
fullName() {
return this.firstName + ' ' + this.lastName;
},
},
그리고 template 태그에 fullName 함수를 적용시키자.
<h1>Hello {{ fullName() }}</h1>
실행해보면 두 데이터를 따로 적은 것과 같은 결과를 얻을 수 있다. 하지만 이렇게 하면 매번 렌더링 할때마다 같은 값을 컴퓨터가 계산하게 된다. 그래서 필요한 기능이 computing 이다. computed안의 데이터는 단 한번만 계산하고 계산된 값을 재활용한다.
computed는 script 태그안에 methods 와 같은 방식으로 선언된다.
<script>
export default {
name: 'computedVue',
components: {},
data() {
return {
};
},
setup() {},
created() {},
mounted() {},
unmouted() {},
methods: {
},
computed: {},
};
</script>
computed에 선언 된 값은 data에 선언 된 값과 완전히 동일한 역할을 한다. computed에 아까와 같은 함수를 선언하고 h1 태그에 적용해보자.
<template>
<div>
<h1>Hello {{ firstName }} {{ lastName }}</h1>
<h1>Hello {{ fullName }}</h1>
</div>
</template>
.
.
.
computed: {
fullName() {
return this.firstName + ' ' + this.lastName;
},
},
computed 안에 생성된 값은 늘 data에서 받아온 값의 변경여부를 체크한다. input에 firstName과 lastName을 v-model로 넣어 확인해보자.
<template>
<div>
<input type="text" v-model="firstName" />
<input type="text" v-model="lastName" />
<h1>Hello {{ fullNameComputed }}</h1>
</div>
</template>
실행해보면 input의 값을 변경하는 즉시 computed되어 렌더링 된 값 또한 바로 변하는 것을 확인 가능하다.
Watch
watch 기능은 computed 기능과 비슷하면서도 다르다.
한번 methods를 사용해 input을 통해 x와 y를 구해와서 결과 값을 z에 넣는 코드를 짜보자.
<template>
<div>
x:<input type="text" v-model.number="x" /> + y:<input
type="text"
v-model.number="y"
/>
<br />
<button @click="addNum">Click to add</button>
<br />
result:<input type="text" v-model.number="z" />
</div>
</template>
<script>
export default {
name: 'watchVue',
components: {},
data() {
return {
x: 0,
y: 0,
z: 0,
};
},
setup() {},
created() {},
mounted() {},
unmouted() {},
methods: {
addNum() {
this.z = this.x + this.y;
},
},
};
</script>
참고로 여기서 v-model.number="" 속성은 값을 Number로 받아옴을 의미한다.
이번에는 한번 watch를 사용해보저. watch는 computed와 같은 방법으로 선언 할 수 있고, 이미 data에 정의된 객체만 사용가능하다.
watch: {
x() {},
},
watch에서는 위에 선언한 x라는 값에 변경 사항이 생기는지 감시한다.
<template>
<div>
x:<input type="text" v-model.number="x" /> + y:<input
type="text"
v-model.number="y"
/>
<br />
<button @click="addNum">Click to add</button>
<br />
result:<input type="text" v-model.number="z" />
</div>
</template>
<script>
export default {
name: 'watchVue',
components: {},
data() {
return {
x: 0,
y: 0,
z: 0,
};
},
setup() {},
created() {},
mounted() {},
unmouted() {},
methods: {
addNum() {
this.z = this.x + this.y;
},
},
watch: {
x() {
this.z = this.x + this.y;
},
y() {
this.z = this.x + this.y;
},
},
};
</script>
이렇게 코딩하면 z 값은 x, 또는 y 값이 바뀔때마다 버튼을 누르지 않아도 자동으로 업데이트 된다.
watch는 자동적으로 업데이트 해주기 때문에 굉장히 편리하지만 많은 자원을 소모하는 기능이다. watch 기능은 반드시 필요한 경우에만 사용하는 것이 좋다.
'개발 > Vue' 카테고리의 다른 글
Vue 이벤트 처리하기 - click/change/key (0) | 2022.04.17 |
---|---|
Vue 렌더링 (0) | 2022.04.17 |
Vue 데이터 바인딩-attribute/class/style (0) | 2022.04.16 |
Vue 데이터 바인딩-html/input/select (0) | 2022.04.16 |
Vue 컴포넌트 기초 (0) | 2022.04.13 |