ref
라는 속성을 통해 해당 하는 요소를 참조할 수 있고 참조된 내용은 $refs에 저장된다.
html이 연결된 직후에만 사용 가능해서, mounted()에만 사용 가능하다. created()에서는 undefined라고 뜸.
또한ref
도 특정한 이름으로 참조가 가능하다.
아래 내용을 콘솔에 찍으려면
App.vue
<template>
<h2>Hello world</h2>
</template>
<script>
export default {
mounted() {
const h2El = document.querySelector('h2')
console.log(h2El.textContent)
}
}
</script>
이렇게 했어야 했다.
하지만! ref
를 이용해서
App.vue
<template>
<h2 ref="hello">
Hello world
</h2>
</template>
<script>
export default {
mounted() {
console.log(this.$refs.hello)
}
}
</script>
이렇게 변경 가능하다.