watch는 감시자 역할을 하고 있으며, 설정한 데이터가 변화할 때 마다 watcher도 실행이 된다
watch : {감시할데이터(){}}
코드 예시 :
watch : {
month(e){
if(isNaN(e) == true || e >=13 ){
alert('One year is 12 months');
this.month = 1;
}
}
},
month
데이터가 변할 때 마다 watcher도 실행 된다.
💡Tip) input type=range 를 주어서 값을 제한줘도 된다.
이에 대한 자세한 설명은 타블로그를 참고 부탁드립니다...
내가 처음 데이터를 셋팅해 놓은것은 [현재 날짜로부터 한달전] ~ [현재 날짜] 이기 때문에 이 날짜 안에 선택된 데이터들만 보였다.
그러나 기획에서 처음에는 [현재 날짜] ~ [현재 날짜] 로만 표시되고 데이터의 기간 필터는 걸지 않았으면 좋겠다고 하셨다.
요약 : 캘린더의 특정 기간을 선택하게 되었을 경우에'만' 필터가 걸려서 데이터가 변경되도록 하고 싶었다.
처음에 셋팅한 [현재 날짜로부터 한달전] ~ [현재 날짜] 코드
/* data */
range: {
start: dayjs().add(-1, 'M').format('YYYY-MM-DD 00:00:00'),
end: dayjs().format('YYYY-MM-DD 23:59:59'),
field: 'regDt',
fieldLabel: '등록 일시',
type: 'date',
label: 'dateSelectedCal',
},
watch: {
range: {
deep: true,
handler(value) {
this.dateSelected(value) //데이터 선택시 실행 함수
},
},
},
methods: {
async initialize() {
this.range = {
start: dayjs().add(-1, 'M').format('YYYY-MM-DD 00:00:00'),
end: dayjs().format('YYYY-MM-DD 23:59:59'),
field: 'regDt',
fieldLabel: '등록 일시',
type: 'date',
label: 'dateSelectedCal',
}
},
나같은 말하는 돌맹이에겐 또 한번의 삽질의 시간...
비동기화하여 처리해야하는지 아니면 처음에 데이터를 다 비워놓고 나중에 데이터를 넣어준다던지.. 이 방법들이 맞는지도 틀린지도 모르고 우선 시작해 보았다.
그러던 도중 조건부 watch
를 우연하게 찾게 되었고 바로 삽질을 끝내고 불필요한 코드를 모두 지울 수 있었다. 얏호
this.$watch
사용 예시
/* Watch a property name */
this.$watch('a', (newVal, oldVal) => {})
/* Watch a dot-delimited path */
this.$watch('a.b', (newVal, oldVal) => {})
/* Using getter for more complex expressions */
this.$watch(
// every time the expression `this.a + this.b` yields
// a different result, the handler will be called.
// It's as if we were watching a computed property
// without defining the computed property itself.
() => this.a + this.b,
(newVal, oldVal) => {}
)
/* Stopping the watcher */
const unwatch = this.$watch('a', cb)
// later...
unwatch()
vue 공식 문서 - https://vuejs.org/guide/essentials/watchers.html#this-watch
this.$watch
를 적용하기 위해선 초기값(range)데이터가 필요하고, 해당 range가 변경 되었을 경우에만 특정함수를 실행하여 값을 변경해주어야 하기 때문에
watch(){} 에 있는 것 range를 지우고 이것을 methods에서 작동할 수 있도록 옮겨주었다.
methods: {
/* this.range = {
start: dayjs().add(-1, 'M').format('YYYY-MM-DD 00:00:00'),
end: dayjs().format('YYYY-MM-DD 23:59:59'),
field: 'regDt',
fieldLabel: '등록 일시',
type: 'date',
label: 'dateSelectedCal',
}
*/
// range 데이터가 변경되는 경우에 watch 실행
this.$watch('range', value => {
this.dateSelected(value)
})
},
기존에는 초기 설정된 한달동안의 range 데이터가 먼저 보이고 그 이후에 값이 보였다면,
this.$watch를 사용한 지금은 처음에 전체의 값이 다 보이고 그 이후에 데이터를 변경하였을 경우에만 필터가 적용되어 선택한 기간의 데이터만 보였다.
아주 유용한 기능인것 같다!