Develop Note by J.S.

[Vue3] Ref, Reactive, Props, Emit type 지정 방법 본문

FrontEnd/Vue3

[Vue3] Ref, Reactive, Props, Emit type 지정 방법

js-web 2023. 6. 16. 12:28
반응형
  • Vue3 에서 타입지정 할 때 Vue3의 타입스크립트가 익숙치 않은 경우 타입지정이 까다롭습니다.
    주로 사용하는 기능에 대한 타입 지정 방법입니다.

1. ref

import { ref } from 'vue'
import type { Ref } from 'vue' 

// 변수에 직접 type을 지정하는 case
const year: Ref<string | number> = ref('2020')

year.value = 2020 // ok!


// or

//ref 함수 호출 시 제네릭으로 타입을 지정하는 case
const year = ref<string | number>('2020')

year.value = 2020 // ok!

2. reactive 

import { reactive } from 'vue'

interface Book {
  title: string
  year?: number
}

// ref와 다르게 wrapping되지않은 reactive는 Object 변수에 타입 지정
const book: Book = reactive({ title: 'Vue 3 Guide' })

3. computed

// 제네릭으로 전달인자의 type을 전달
const double = computed<number>(() => {
  // type error if this doesn't return a number
})

4. defineProps 

const props = defineProps({
  foo: { type: String, required: true },
  bar: Number
})

//or

const props = defineProps<{
  foo: string
  bar?: number
}>()

5. defineEmits

// runtime 선언 방식
const emit = defineEmits(['change', 'update'])

//or 

//type기반
const emit = defineEmits<{
  (e: 'change', id: number): void
  (e: 'update', value: string): void
}>()

 

 

 

참고사이트
https://v3-docs.vuejs-korea.org/guide/typescript/composition-api.html

반응형

'FrontEnd > Vue3' 카테고리의 다른 글

[Vue3] v-model  (0) 2023.06.28
[Vue3] Watch  (0) 2023.06.19
[Vue3] Computed  (0) 2023.06.19
[Vue3] Composition API(2)  (0) 2023.06.19
[Vue3] Composition API(1)  (0) 2023.06.16