Vue.js에서 ref는 DOM 요소나 컴포넌트 인스턴스에 직접 접근할 수 있는 유용한 방법입니다. Vue 3에서는 ref가 컴포넌트 내부에서 반응성 데이터를 생성하는 데도 사용됩니다.
<template>
<div>
<input ref="inputRef" type="text" placeholder="Enter text" />
<button @click="focusInput">Focus Input</button>
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
setup() {
const inputRef = ref(null); // DOM 요소에 대한 참조를 생성
const focusInput = () => {
inputRef.value.focus(); // DOM 요소에 접근하여 focus() 메서드 호출
};
return {
inputRef,
focusInput
};
}
};
</script>
주요 개념:
ref는 setup 함수 안에서 선언됩니다.
ref로 지정한 DOM 요소는 inputRef.value로 접근합니다.
DOM에 접근하려면 onMounted 훅을 사용하여 컴포넌트가 마운트된 후에만 DOM 요소에 접근할 수 있습니다.
<template>
<div>
<p>Counter: {{ counter }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const counter = ref(0); // 반응성 변수
const increment = () => {
counter.value++; // 반응성 데이터 업데이트
};
return {
counter,
increment
};
}
};
</script>
주요 개념:
반응성 변수는 ref(초기값)을 통해 생성됩니다.
counter는 counter.value로 값을 읽거나 업데이트할 수 있습니다.
Vue는 ref로 정의된 변수를 자동으로 반응성 시스템에 등록하여, 값이 변하면 해당 값에 의존하는 템플릿이나 컴포넌트가 자동으로 업데이트됩니다.
<template>
<div>
<ChildComponent ref="childRef" />
<button @click="callChildMethod">Call Child Method</button>
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
setup() {
const childRef = ref(null);
const callChildMethod = () => {
childRef.value.someChildMethod(); // 자식 컴포넌트의 메서드 호출
};
return {
childRef,
callChildMethod
};
}
};
</script>
주요 개념:
자식 컴포넌트에 대한 참조는 ref를 통해 만들 수 있으며, childRef.value로 해당 컴포넌트의 메서드나 속성에 접근할 수 있습니다.
요약:
ref는 Vue에서 DOM 요소나 컴포넌트 인스턴스에 접근하거나, 반응성 변수를 생성하는 데 사용됩니다.
ref를 통해 선언된 값은 .value로 접근 및 변경할 수 있습니다.
반응성 데이터나 컴포넌트의 DOM 및 메서드에 접근할 때 매우 유용합니다.
이 기본적인 사용법을 바탕으로 Vue.js에서 ref를 활용할 수 있습니다.