Front-end/Vue.js
[Vue.js] 데이터 변경 감시 Watch
ImYena
2021. 11. 9. 23:45
728x90
Watch
- 컴포넌트의 데이터 변경 시 자동으로 핸들러 호출
- 유효성 검사에 용이
- computed: 랑은 목적이 다름
- computed: 는 기존의 데이터를 수정하여 새로운 데이터를 만드는데 목적
예시
<template>
<div class="card">
<div class="card-header">
Exam02Watch
</div>
<div class="card-body">
<div class="form-group row">
<label class="col-sm-2 col-form-label">UserId</label>
<div class="col-sm-10">
<input type="text" class="form-control" v-model="userId">
</div>
</div>
<hr/>
<form>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" v-model="product.name">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Company</label>
<div class="col-sm-10">
<input type="text" class="form-control" v-model="product.company">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Price</label>
<div class="col-sm-10">
<input type="number" :class="`form-control ${bgColor}`" v-model.number="product.price">
</div>
</div>
</form>
<hr/>
<button @click="handleButton" class="btn btn-info btn-sm">product 객체 변경</button>
</div>
</div>
</template>
<script>
export default {
name:"Watch",
data() {
return {
userId: "user1",
product: {
name: "정장",
company: "한섬",
price: 1000000
},
bgColor: ""
};
},
methods: {
handleButton() {
this.product = {
name: "정장2",
company: "한섬2",
price: 2000000
}
}
},
watch: {
userId(newValue, oldValue) {
console.log("newValue: ", newValue);
console.log("oldValue: ", oldValue);
console.log("this.userId: ", this.userId);
},
//객체의 속성값만 변경되었을 경우 객체 자체는 동일, newValue랑 oldValue 동일
//객체 자체가 변경되었을 경우에만 데이터 변경 인식
product: {
deep: true,
handler(newValue, oldValue) {
console.log("newValue: ", newValue);
console.log("oldValue: ", oldValue);
}
},
"product.name"(newValue, oldValue) {
console.log("newValue: ", newValue);
console.log("oldValue: ", oldValue);
console.log("this.product.name: ", this.product.name);
},
"product.price"(newValue, oldValue) {
if(newValue < 0) {
this.bgColor = "bg-danger";
} else if(newValue >= 0 && newValue <= 100000){
this.bgColor = "bg-success";
} else {
this.bgColor = "bg-primary";
}
}
}
}
</script>
- 객체 데이터 변경 감시의 경우 주의
728x90
반응형