똑같은 삽질은 2번 하지 말자

Vue Composition API 에서 props를 watch하기 본문

카테고리 없음

Vue Composition API 에서 props를 watch하기

곽빵 2021. 11. 7. 20:21

해결(결과)

props을 watch하기 위해서 결론부터 적자면 화살표 함수한번 감싸주거나

  props: {
    onEdit: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  setup(props, { emit }) {
    watch(
      () => props.onEdit,
      (cur: Boolean, prev: Boolean): void => {
        console.log(cur, prev)
      },
    )
  },

 

toRefs로 반응성을 입혀서 반환시켜줘야한다.

  setup(props, { emit }) {
    const onEdit = toRefs(props).onEdit
    watch(onEdit, (cur: Boolean, prev: Boolean): void => {
      console.log(cur, prev)
    })
  },

 

실수하기 좋은 패턴 & 문제(원인)

일반적으로 짜기 쉬운 코드는 밑과 같은데

  props: {
    onEdit: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  setup(props, { emit }) {
    watch(
      props.onEdit,
      (cur: Boolean, prev: Boolean): void => {
        console.log(cur, prev)
      },
    )
  },

이렇게 하면 param 타입이 맞지않는다고 경고를 받는다. 

console.log
in Editor

 

여기서 그 이유는 setup(props) 에서 props는 자동적으로 reactive로 씌워져서 온다.

onEdit 이외의 여러 속성들을 추가해서 setup에서 출력시킨결과

reactive가 씌워진 친구들은 그 객체 자체는 반응성을 가지지만 하나하나의 요소(객체.요소)들은 반응성을 가지지 못함으로써

console.log('props', props.onEdit)

props.onEdit은 반응성을 가지고 있지 않은 그냥 순수 boolean값에 지나지 않는다.

 

vue의 watch에 관한 공식문서를 보면 

 

Computed and watch | Vue.js

Computed and watch This section uses single-file component syntax for code examples computed Takes a getter function and returns an immutable reactive ref object for the returned value from the getter. const count = ref(1) const plusOne = computed(() => co

v3.vuejs.org

GitHub

 

GitHub - vuejs/composition-api: Composition API plugin for Vue 2

Composition API plugin for Vue 2. Contribute to vuejs/composition-api development by creating an account on GitHub.

github.com

watch의 첫번째 인자로써는 이하의 로그들에 출력된 것과 같이 반응성을 가진 객체, getter함수 같은것들만 올 수 있다.

console.log

props.onEdit을 전달하는건 그냥 원시적인 boolean값을 전달하는 것에 지나지 않으므로 잘못된 param으로 인식하는것이다.

그러므로 화살표함수로 감싸주거나 반응성을 입혀서 전달해 주어야 watch를 할 수 있게되는것이다.

 

참고자료

 

https://stackoverflow.com/questions/59125857/how-to-watch-props-change-with-vue-composition-api-vue-3

 

How to Watch Props Change with Vue Composition API / Vue 3?

While Vue Composition API RFC Reference site has many advanced use scenarios with the watch module, there is no examples on how to watch component props? Neither is it mentioned in Vue Composition...

stackoverflow.com

 

props뿐만 아니라 ref도 밑에처럼 해야한다.

strSort만 하면 이상하게 반응이 안됬었는데 @vue/composition-api 을 쓰는것도 vue3에서 직접 끌어다가 쓰는게 다를지도?

watch는 reactive한 속성을 가진 변수가 오면 되니깐 이하처럼 하면된다.

strSort = ref("") 임

watch(
  strSort,
  (): void => {
    nextTick(() => {
      if (isProcessing.value) return
      isProcessing.value = true
      const node_category = document.getElementById('categories')
      if (joinOptions.value.length > 0) {
        node_category.removeAttribute('disabled')
      } else {
        node_category.setAttribute('disabled', 'true')
      }

      // TODO: Vue3対応必要
      const filterForm = context.refs.filter_form as HTMLFormElement
      filterForm.submit()
    })
  },
)
Comments