특정한 요소나 컴포넌트를 참조 할 수 있다.
html 에서 우리가 원하는 요소를 찾을때 class 혹은 id 를 사용했었다.
그와 비슷하게 vue 에서도 원하는 요소를 찾고 참조하고 싶을 때 **ref** 를 사용한다.
**주의!**
html 에서 요소를 찾기 위해서는 컴포넌트가 html 과 연결 된 이후여야 한다.
created() 에서는 사용할 수 없다. undefined!
mounted() 에서 사용 가능하다.
<template>
<h1 ref="hello">
Hello world!
</h1>
</template>
<script>
export default {
mounted() {
console.log(this.$refs.hello)
}
}
</script>
// 컴포넌트에서 ref 사용을 해보자.
// App.vue
<template>
<Hello ref="hello" />
</template>
<script>
import Hello from "~/components/Hello"
export default {
components: {
Hello
},
mounted() {
console.log(this.$refs.hello)
}
}
</script>
=====================================================================
// Hello.vue
<template>
<h1>
Hello~
</h1>
</template>
this.$refs.hello
proxy 객체가 나온다. target 과 handler 가 들어있다.
target 을 열어보면 $ 사인의 어려가지 속성이 있다.
컴포넌트를 ref 라는 속성으로 참조하고 있다면 target 의 $el 을 사용해야 한다.
console.log(this.$refs.hello.$el)
이제 <h1>Hello~</h1> 가 출력된다.
=================================================================================
el 은 최상위 요소 하나를 가리킨다. 만약 Hello 컴포넌트에서 2개 이상의 요소가 있다면?
<template>
<h1>
Hello~
</h1>
<h1>
Good?
</h1>
</template>
이제 el 은 무엇을 가리켜야 하는지 모른다. 원하는 요소를 기리키게 해보자.
this.$refs.hello.$refs.good
refs.hello 의 refs.good 을 찾는다.
// App.vue
<template>
<Hello ref="hello" />
</template>
<script>
import Hello from "~/components/Hello"
export default {
components: {
Hello
},
mounted() {
console.log(this.$refs.hello.$refs.good)
}
}
</script>
// Hello.vue
template>
<h1>
Hello~
</h1>
<h1 ref="good">
Good?
</h1>
</template>
// <h1>Good?</h1> 이 출력된다.