Vue2의 watch에서는 감시하지만, Vue3의 watch에서는 감시하지 못하는 이유
현우
watch: {
iocList: (val) {
this.watchIocList(val);
}
}watch(iocList, (val) => watchIocList(val));// vue2
this.iocList.push({ value: 'abcd' });
// vue3
iocList.value.push({ value: 'abcd' });
// Vue 2 내부 동작 (실제 구현과 유사)
const methodsToPatch = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse']
methodsToPatch.forEach(method => {
const original = Array.prototype[method]
def(arrayProto, method, function mutator(...args) {
const result = original.apply(this, args)
const ob = this.__ob__
ob.dep.notify() // ← 참조 변경 없이 직접 알림!
return result
})
})watch(iocList, (val) => watchIocList(val), { deep: true });iocList.value = [...iocList.value, { value: 'abcd' }]// Vue2에서는 접근이 되지 않는다.
this.list[0] = 'new value';
// Vue2에서는 이렇게 접근해야한다.
this.$set(this.list, 0, 'new value');
Vue.set(this.list, 0, 'new value');
// Vue3에서는 가능하다.
list.value[0] = 'new value';// Vue2에서는 감지가 되지 않는다.
this.obj.newKey= 'value';
delete this.obj.existingKey;
// Vue2에서는 이렇게 추가 및 삭제해야한다.
this.$set(this.obj, 'newKey', 'value');
this.$delete(this.obj, 'existingKey');
// Vue3에서는 가능하다.
obj.value.newKey = 'value';
delete obj.value.existingKey;// Vue2에서는 감지하지 못한다.
this.list.length = 0;
//
this.list.splice(0);
// Vue3에서는 가능하다.
list.value.length = 0;// Vue 2 ❌ 나중에 추가한 속성은 반응성 없음
export default {
data() {
return { obj: {} } // 처음에 없던 속성은 반응성 X
},
mounted() {
this.obj.name = 'test' // ❌ 반응성 없음!
}
}
// Vue 3 ✅ 언제 추가해도 반응성 있음// Vue 2 - 반응성 한계 때문에 강제 업데이트 메서드가 있었음
this.$forceUpdate()