본문 바로가기

Vue/Vue

Vuex4에서 state 변경을 감지하는법 (watchEffect)

Vue.js 에서 컴포넌트를 나누면서 재사용이 많은 데이터를 Vuex 에 보관하기 시작했고

Vuex의 상태값 변화에 따라 데이터를 갱신해야 하는 일이 생겼습니다.

 

Vue.js 2.0 에서

Vue.js 2 (Vuex 3) 버전에서는 computed와 watch를 사용하여 아래와 같이 state 변경을 감지합니다

 

...
computed: {
    getData () {
        return this.$store.getters.getPlaces
    }
},
watch: {
    getData (val) {
        console.log('watched: ', val)   
    }
},
...

 

computed : "반응형 getter" 즉 함수내에 속한 프로퍼티 (state) 의 변경여부를 추적합니다.

watch : computed 객체의 변경 (get, set) 을 감시하여 변경이 이루어지면 컴포넌트의 지역 변수에 할당합니다.

 

Vue.js 3.0 에서

Vue.js 3.0 에서는 setup() 안에서 computed 로 변경여부 추적이, 그리고 Vue.js 3.0부터 지원하는 watchEffect 에서 computed 객체의 변경 감지가 이루어집니다

 

 import {computed, watchEffect} from "vue";
 setup() {
    const store = useStore();
    const places = computed(() => store.getters["places/getPlaces"]);

    watchEffect(()=>{
      console.log(places)
    })
    return{ places }
  },

 

watchwatchEffect의 차이점을 간단하게 알아보자면

  • watch 는 이전값과 변경된 값을 알 수 있지만, watchEffect는 변경된 값만 가져옵니다.
  • watch 는 특정 데이터 변경에 따라 실행되어 lazy 하지만, watchEffect 는 의존성이 있는 데이터에 대해 immediately 합니다
  • watch 는 감시 대상을 지정해야 하지만 watchEffect는 함수 안에서 참조되는 변수만 감시합니다

이에 대한 이점으로 watchEffect 에서는 우리가 보고자 하는 값을 수동으로 선언 할 필요가 없습니다.

아래 코드는 다음 페이지에서 자세히 볼 수 있습니다

 

import { watchEffect, ref, computed } from 'vue'
import SomeSliderAPI from 'third-party-slider'

const props = defineProps({
  slidesPerGroup: { type: Number, default: 5 },
  touchEnabled: { type: Boolean, default: true },
  smoothScrolling: { type: Boolean, default: true }
})

watchEffect(() => {
  SomeSliderAPI.setOptions({
    slidesPerGroup: props.slidesPerGroup,
    touchEnabled: props.touchEnabled,
    smoothScrolling: props.smoothScrolling
  })
})

 

 

만약 컴포넌트에 더 많은 Props 가 있다고 생각해보면 얼마나 불편할까요

위 코드를 스프레드 연산자를 사용하여 리펙터링이 가능합니다

 

import { watchEffect, ref, computed } from 'vue'
import SomeSliderAPI from 'third-party-slider'

const props = defineProps({
  slidesPerGroup: { type: Number, default: 5 },
  touchEnabled: { type: Boolean, default: true },
  smoothScrolling: { type: Boolean, default: true }
})

watchEffect(() => {
  SomeSliderAPI.setOptions({ ...props })
})

 

 

'Vue > Vue' 카테고리의 다른 글

Vuex4 모듈화, store호출 (2)  (0) 2023.04.06
Vuex란? (1)  (0) 2023.04.05
Vue3) Vue-Router  (0) 2023.04.05
Vue.js 3.0 시작하기  (0) 2023.04.05
로그아웃 3 (Springboot + Vue)  (0) 2022.01.25