특정 데이터의 변화를 감지하여 자동으로 특정 로직을 수행해주는 속성
new Vue({
data() {
return {
message: 'Hello'
}
},
watch: {
message: function(value, oldValue) {
//message의 값이 변할 때마다 watch 속성에 정의한 message 함수가 실행되면서 콘솔에 변한 데이터 출력
console.log(value);
}
}
})
watch 대상 속성에 함수를 연결하는 대신 메서드 함수를 연결할 수 있습니다
new Vue({
data() {
return {
message: 'Hello'
}
},
methods: {
logMessage() {
console.log(this.message);
}
},
watch: {
'message': 'logMessage' // 대상 속성과 메서드 함수를 매칭
}
})
watch 대상 속성에 아래와 같이 handler()와 immediate 속성을 정의할 수 있습니다.
new Vue({
data() {
return {
message: 'Hello'
}
},
watch: {
'message': {
handler(value, oldValue) {
console.log(value);
},
immediate: true // 컴포넌트가 생성되자마자 즉시 실행
}
}
})
변경 전
watch : {
async isTabVisible(newVal, oldVal){
await this.$nextTick();
//탭이 사라질 때면 기다려서 list가 undefined
//이상하게 처음에는 ref로 v-if, v-else를 모두 인식하는지 class=empty가 뜬다
if(this.$refs.list){
//아예 undefined로 안 들어온다
if(newVal === false && oldVal === true){
this.listScrollLeft = this.$refs.list.scrollLeft
}
if(newVal === true && oldVal === false){
this.$refs.list.scrollLeft = this.listScrollLeft
}
}
}
변경 후
watch: {
async isTabVisible(newVal, oldVal) {
if (newVal === false && oldVal === true) {
//탭이 사라질 때 list는 항상 있다
//scroll 저장해두기
this.listScrollLeft = this.$refs.list.scrollLeft;
} else {
//생길 때는 empty일 때니까 list가 생길 때까지 기다렸다가 넣는다
await this.$nextTick();
this.$refs.list.scrollLeft = this.listScrollLeft;
}
}
},