Vue에서 Template Refs는 컴포넌트 내의 특정 DOM 요소나 자식 컴포넌트에 직접 접근할 수 있게 해주는 기능입니다. 이를 통해 DOM 조작이나 자식 컴포넌트의 메소드 호출 등, 보다 세부적인 제어가 가능합니다. 일반적으로 Vue는 데이터를 기반으로 UI를 업데이트하는 선언적 방식을 따르지만, 때로는 특정 요소에 직접적으로 접근하여 조작해야 하는 상황이 있을 수 있습니다. 이때 Template Refs가 유용합니다.
<template>
<div>
<input ref="inputElement" type="text" />
<button @click="focusInput">Focus Input</button>
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
setup() {
// inputElement에 대한 참조를 설정
const inputElement = ref(null);
const focusInput = () => {
// DOM 요소에 접근
inputElement.value.focus();
};
return {
inputElement,
focusInput
};
}
};
</script>
위 예시 코드에서는 DOM 요소에 focus를 부여하는 방식으로 ref 속성이 사용되었습니다.
자식 컴포넌트
<template>
<div>
<p>Child Component</p>
</div>
</template>
<script>
export default {
methods: {
sayHello() {
console.log('Hello from Child Component!');
}
}
}
</script>
부모 컴포넌트
<template>
<div>
<ChildComponent ref="childComponent" />
<button @click="callChildMethod">Call Child Method</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
callChildMethod() {
// 자식 컴포넌트의 메소드 호출
this.$refs.childComponent.sayHello();
}
}
}
</script>