컴포넌트-Refs

토리최고·2022년 1월 18일
0

Vue 문법

목록 보기
20/20
post-thumbnail

Ref (Referece)

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>

이렇게 변경 가능하다.

0개의 댓글

관련 채용 정보