Vue/Vue.js 문법
Vue.js 문법 - Refs
IT Blue
2021. 7. 18. 20:55
Refs
App.vue
<template>
<h1 ref="hello">
Hello World!
</h1>
</template>
<script>
export default {
mounted() {
// <h1> Hello World! </h1>
console.log(this.$refs.hello)
}
}
</script>
코드 이해하기
- ref 속성은 reference 단어의 약어
- ref 속성을 이용해서 레퍼런스 ID를 자식 컴포넌트나 HTML 요소에 부여함으로써 직접 접근할 수 있다
컴포넌트 Refs 예제
App.vue
<template>
<Hello ref="hello" />
</template>
<script>
import Hello from '~/components/Hello'
export default {
components: {
Hello
},
mounted() {
// <h1>Hello~</h1>
console.log(this.$refs.hello.$el)
}
}
</script>
Hello.vue
<template>
<h1>Hello~</h1>
<!-- <h1>Good~</h1> 요소가 추가되면 정확하게 알 수 없다 -->
</template>
코드 이해하기
- 컴포넌트를 ref 속성으로 참조할 경우에는 참조된 이름 뒤쪽에 $el 속성을 명시 (this.$refs.hello.$el)
- 해당 컴포넌트가 참조하는 요소가 출력됨
- 만약 참조하려는 컴포넌트 최상위 요소가 여러 개인 경우에는 어떠한 요소를 참조할지 정확히 알 수 없다
- 그래서 특정한 요소가 아닌 객체 데이터가 출력됨
최상위 요소가 2개인 컴포넌트 Refs 예제
App.vue
/* template 생략 */
<script>
import Hello from '~/components/Hello'
export default {
components: {
Hello
},
mounted() {
// <h1> Good? </h1>
console.log(this.$refs.hello.$refs.good)
}
}
</script>
Hello.vue
<template>
<h1>Hello~</h1>
<h1 ref="good">
Good?
</h1>
</template>
코드 이해하기
- $el 속성 대신에, $refs 속성 다음에 컴포넌트에 참조된 ref 이름을 명시 (this.$refs.hello.$refs.good)