본문 바로가기

Front-end/Vue

Vue.js) 컴포넌트 - Refs

1. Refs

Vue.js에서 refs는 DOM 요소나 자식 컴포넌트를 직접 참조할 수 있는 방법을 제공합니다. 이는 주로 DOM 조작이나 자식 컴포넌트의 메서드 호출에 사용됩니다. 

 

2. 사용 예제

<template>
	<h1 id="hello">Hello world!</h1>
	<h1 ref="hello">Hello world!</h1>
</template>

<script>
import Hello from './components/HelloComponent.vue';
export default {
	created() {
		console.log('created');
		const h1El = document.querySelector('#hello');
		console.log(this.$refs.hello);
		console.log(h1El);
	},
	mounted() {
		console.log('mounted');
		const h1El = document.querySelector('#hello');
		console.log(this.$refs.hello);
		console.log(h1El.textContent);
	},
};
</script>

라이프사이클이 created 일 땐 html 구조에 연결되기 전이기 때문에 undefined, null로 출력되지만 mounted 일땐 해당 엘리먼트가 출력됩니다. ref는 document.querySelector처럼 태그에 ref 속성으로 명시한 것을 $표시로 찾아 불러올 수 있습니다. 

 

2-1. 자식 컴포넌트 엘리먼트 참조 

// App.vue
<template>
	<Hello ref="hello" />
</template>

<script>
import Hello from './components/HelloComponent.vue';
export default {
	mounted() {
		console.log('mounted');
		console.log(this.$refs.hello2.$refs);
        console.log(this.$refs.hello2.$refs.good);
	},
	components: {
		Hello,
	},
};
</script>

// HelloComponent.vue
<template>
	<h1>Hello~</h1>
	<h1 ref="good">Good~</h1>
</template>

자식 컴포넌트를 호출할 때 refs 를 명시하고 refs 명시된 엘리먼트를 명시해 주면 찾을 수 있습니다.