ref 객체를 반환하며 반환 값 내부에 .value 라는 한 개의 프로퍼티를 가지며 vue 에서는 특정 컴포넌트의 정보(변수,함수..)에 접근하여 DOM 을 직접적으로 컨트롤 할 때 사용한다.
접근하고자 하는 DOM 에 ref="네이밍" 으로 명시한 뒤,
주의할 점은, ref는 DOM에 직접적으로 접근하는 지시어이기 때문에 컴포넌트가 렌더링 된 후, 즉 mounted() hook 에서 사용해야 한다. 만약 created() hook 에서 ref 를 통해 특정 DOM에 접근한다면 undefined 에러가 출력될 것이다.
// index.vue (상위 component)
<template>
<div>
<pop-up ref="popUp" />
<button @click="openPopUp">팝업 확인</button>
</div>
</template>
<script setup>
import {ref} from 'vue'
import popUp from './popUp'
const popUp = ref(null)
cons openPopUp = () => {
popUp.value.open()
}
</script>
// popUp.vue (하위 component)
<template>
<teleport to="body">
<div v-if="state.isVisible">
<div v-click-outside="outsideClick">
<slot></slot>
</div>
</div>
</teleport>
</template>
<script setup>
import { directive as vClickOutside } from 'click-outside-vue3'
import { reactive } from 'vue'
const props = defineProps({
isOutsideClick: {
type: Boolean,
default: true,
},
})
const state = reactive({
isVisible: false,
})
// 상위 컴포넌트에서 해당 함수들에 접근.
const open = () => {
state.isVisible = true
}
const close = () => {
state.isVisible = false
}
const outsideClick = () => {
if (props.isOutsideClick) {
state.isVisible = false
}
}
defineExpose({
outsideClick,
close,
open,
})
</script>
popUp.value를 console.log로 찍어보면, 해당 컴포넌트에서 정의한 3개의 함수를 확인할 수 있다.
ref, reactive 모두 컴포넌트를 반응형 즉, 어떤 액션에 대한 리액션이 실시간으로 동작하도록 만들어준다.
1) reactive는 자바스크립트의 원시값 할당이 불가능하며, 객체 할당 만 가능하고, ref는 객체는 물론 원시값도 할당 할 수 있다.
const reactiveDaTum = reative(1) // wrong
const refDaTum = ref(1) // right
const state = reactive({
title : 'vue 공부',
isValid : true,
})
2) reactive 객체 재할당이 불가능하지만, ref는 가능하다.
// wrong
const testReative = reative({title : 'vue 공부'})
testReactive = {title : 'vue 공부', subTitle : 'ref'}
// right
const testRef = ref({title : 'vue 공부'})
testRef = {title : 'vue 공부', subTitle : 'ref'}
// right
const testReative = reative({title : 'vue 공부'})
testReactive.title = 'vue 3 문법'
reative는 원시값들의 그룹화 선언이 필요할 때 주로 사용되고,
ref는 원시값 할당 혹은 객체의 재할당이 필요한 경우에 활용할 수 있다.
//reactive 사용
const info = reactive({
project: 'vue3',
participants: ['violet', 'zack', 'colin'],
nuxt: true,
});
//ref 사용
const projectName : ref('vue3')
const participants : ref(['violet', 'zack', 'colin'])
const nuxt : ref(true)
const info = ref({
project: 'vue3',
participants: ['violet', 'zack', 'colin'],
nuxt: true,
});