unref

  • argument 가 ref 인 경우 내부 value return
function useFoo(x: number | Ref<number>) {
  const unwrapped = unref(x) // unwrapped is guaranteed to be number now
}

toRef

  • 반응성 객체에 ref 사용할 때 씀
  • prop로 ref 넘길 때 용이
const state = reactive({
  foo: 1,
  bar: 2
})

const fooRef = toRef(state, 'foo')

fooRef.value++
console.log(state.foo) // 2

state.foo++
console.log(fooRef.value) // 3
export default {
  setup(props) {
    useSomeFeature(toRef(props, 'foo'))
  }
}

toRefs

  • 일반 객체에서 반응성 객체로 바꿈
  • 여기서 결과 객체의 각 속성은 원본 객체의 해당 속성을 가리키는 참조
  • 반응성 객체를 반환 시 용이
const state = reactive({
  foo: 1,
  bar: 2
})

const stateAsRefs = toRefs(state)
/*
Type of stateAsRefs:

{
  foo: Ref<number>,
  bar: Ref<number>
}
*/

// The ref and the original property is "linked"
state.foo++
console.log(stateAsRefs.foo) // 2

stateAsRefs.foo.value++
console.log(state.foo) // 3
function useFeatureX() {
  const state = reactive({
    foo: 1,
    bar: 2
  })

  // logic operating on state

  // convert to refs when returning
  return toRefs(state)
}

export default {
  setup() {
    // can destructure without losing reactivity
    const { foo, bar } = useFeatureX()

    return {
      foo,
      bar
    }
  }
}

isRef

  • ref 객체 값 체크

isProxy

  • reactive 이거나 readonly 일 때 객체 체크

isReacitve

  • reactive에 의해 만들어진 반응형 proxy 객체 체크
  • 만약 프록시가 readonly로 만들어 진경우 true return
  • 다른 프록시가 reactive에 의해 만들어진 다른 프록시가 감쌈

isReadonly

  • readonly로 만들어진 객체가 readonly인지 체크

'Vue.js > vue3' 카테고리의 다른 글

[vue3] composition API  (0) 2020.09.30
[vue3] Reactivity APIs  (0) 2020.07.02
[vue3] setup  (0) 2020.07.02
[vue3] vue 2 > vue3  (0) 2020.07.02

setup

  • 새로운 옵션
  • 컴포넌트 안에서 composition api 사용하는 진입점

호출 시점

  • 컴포넌트 instance가 생성될때 props 초기화 이후
  • beforeCreate 훅 이전에 호출
  • object 반환
  • object 속성은 컴포넌트 템플릿에서 사용된다
<template>
  <div>{{ count }} {{ object.foo }}</div>
</template>

<script>
  import { ref, reactive } from 'vue'

  export default {
    setup() {
      const count = ref(0)
      const object = reactive({ foo: 'bar' })

      // expose to template
      return {
        count,
        object
      }
    }
  }
</script>

setup을 통해서 반환되는 refs는 자동적으로 템플릿 접근 시 감싸있지 않다. 그래서 .value를 사용할 필요가 없다

  • setup은 render 함수를 반환 할 수 있음

    같은 범주에 선언되어 있는 reative state를 바로 접근 할 수 있게 해줌

import { h, ref, reactive } from 'vue'

export default {
  setup() {
    const count = ref(0)
    const object = reactive({ foo: 'bar' })

    return () => h('div', [count.value, object.foo])
  }
  • aruguments

    • props의 첫번째 인자를 함수에서 받음

        export default {
          props: {
            name: String
          },
          setup(props) {
            console.log(props.name)
          }
        }
    • props 객체는 반응성임

      watchEffect, watch로 새로운 props가 전달될 때 확인할 수 있음

        export default {
          props: {
            name: String
          },
          setup(props) {
            watchEffect(() => {
              console.log(`name is: ` + props.name)
            })
          }
        }

      props객체를 해체를 하면 반응성을 잃음

        export default {
          props: {
            name: String
          },
          setup({ name }) {
            watchEffect(() => {
              console.log(`name is: ` + name) // Will not be reactive!
            })
          }
        }

      props객체는 개발하는 동안 불변

      만약, 사용자 코드를 변경하려고 시도하면 경고함

      setup의 두번째 인자는 context 객체(vue2와 this처럼 ) 제공

        const MyComponent = {
          setup(props, context) {
            context.attrs
            context.slots
            context.emit
          }
        }

      attrs와 slots는 내부 구성요소의 proxy

      이를 통해 항상 최근 값을 노출하고 오래된 참조에 접근 하지 않고도 값을 구조화 할 수 있음

        const MyComponent = {
          setup(props, { attrs }) {
            // 최근 상테를 가져옴
            function onClick() {
              console.log(attrs.foo) // 가장 최근 참조 보장
            }
          }
        }
  • this

    setup()에서는 사용 불가

'Vue.js > vue3' 카테고리의 다른 글

[vue3] Reactivity Utilities  (0) 2020.09.30
[vue3] composition API  (0) 2020.09.30
[vue3] Reactivity APIs  (0) 2020.07.02
[vue3] vue 2 > vue3  (0) 2020.07.02

+ Recent posts