본문 바로가기
프론트엔드/Vue.js

컴포넌트 - Refs

by step 1 2021. 8. 4.
반응형

ref: 선언된 요소를 참조할 때 사용하는 속성

 

라이프 사이클 속성중 mounted 에서는 사용 가능 하지만 created에서는 사용이 불가능 하다.

 

기본 코드

App.vue

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

<script>
export default {
  mounted() {
    const h1El = document.querySelector('#hello')
    console.log(h1El.textContent)
  }
}
</script>

브라우저 확인

 

수정한 코드

App.vue

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

  <h1 ref="hello">
    Hello world2!
  </h1>

  <Hello ref="hello2" />
</template>

<script>
import Hello from '~/components/Hello'

export default {
  components: {
    Hello
  },
  created () {
    // console.log("ref: " + this.$refs.hello.textContent)
    // console.log("ref2: " + this.$refs.hello2.textContent)
  },
  mounted() {
    const h1El = document.querySelector('#hello')
    console.log(h1El.textContent)
    // console.log("ref: " + this.$refs.hello.textContent)
    console.log("ref: " + this.$refs.hello)
    // 컴포넌트를 이용할 때에는 $el이라는 속성을 주어야 한다.
    console.log("ref2: " + this.$refs.hello2.$el.textContent)
    // 컴포넌트 내부에 객체가 여러개일 경우에는 refs를 이용해서 정의해 주어야 한다.
    console.log("ref2: " + this.$refs.hello2.$refs.good.textContent)
  }
}
</script>

Hello.vue

<template>
  <h1>Hello!</h1>
  <h1 ref="good">
    Good!
  </h1>
</template>

 

브라우저 확인

 

반응형

'프론트엔드 > Vue.js' 카테고리의 다른 글

컴포지션 API - 기본옵션과 라이프사이클  (0) 2021.08.05
컴포지션 API - 반응형 데이터  (0) 2021.08.05
컴포넌트 - Provide, Inject  (0) 2021.08.04
컴포넌트 - slot  (0) 2021.08.04
컴포넌트 - Emit  (0) 2021.08.04