써치킴의 우당탕탕 개발 블로그

[Vue.js][Ch2][Vue 문법] 컴포넌트 - Refs 본문

완벽하게 Vue.js

[Vue.js][Ch2][Vue 문법] 컴포넌트 - Refs

써치킴 2022. 4. 19. 21:38

Ref

vue.js에서 제공하는 Refence의 약어로 '요소를 참조하겠다'는 의미이다.

컴포넌트가 HTML 구조와 연결된 직후에만 사용 가능하다.

=> mounted 라이프 사이클에서 사용 가능, created 라이프 사이클에서 사용 불가능

 

App.vue

<template>
  <!-- ref : reference의 약어 -->
  <h1 ref="hello">   <!-- h1 태그 요소를 hello라는 이름으로 참조하겠다. -->
    Hello World!
  </h1>
</template>

<script>
export default {
  created() {   // 컴포넌트가 생성된 직후
    console.log(this.$refs.hello);
  }, 
  mounted() {   // 컴포넌트가 HTML 구조와 연결된 직후
    console.log(this.$refs.hello);
    console.log(this.$refs.hello.textContent);
  }
}
</script>

출력

컴포넌트를 ref를 이용해서 참조할 경우

최상위 요소가 1개일 때 콘솔에 뽑아보면

 

 

 

 

 

 

 

Target > $el은 최상위 요소를 의미한다.

 

 

 

 

 

 

 

App.vue

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

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

export default {
  components : {
    Hello
  },
  mounted() {   // 컴포넌트가 HTML 구조와 연결된 직후
    console.log(this.$refs.hello.$el);
  }

}
</script>

Hello.vue

<template>
  <h1>Hello~</h1>
</template>

출력

최상위 요소가 여러 개일 때

하위 컴포넌트의 특정 요소에 ref 속성을 추가하고 상위 컴포넌트에서 $refs를 사용

 

App.vue

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

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

export default {
  components : {
    Hello
  },
  mounted() {   // 컴포넌트가 HTML 구조와 연결된 직후
    console.log(this.$refs.hello.$refs.good);
  }

}
</script>

Hello.vue

<template>
  <h1>Hello~</h1>
  <h1 ref="good">Good?</h1>
</template>

출력

Comments