Vue - Template Refs

h.Im·2024년 9월 11일
0

Vue 기초

목록 보기
17/28
post-thumbnail

Vue에서 Template Refs는 컴포넌트 내의 특정 DOM 요소나 자식 컴포넌트에 직접 접근할 수 있게 해주는 기능입니다. 이를 통해 DOM 조작이나 자식 컴포넌트의 메소드 호출 등, 보다 세부적인 제어가 가능합니다. 일반적으로 Vue는 데이터를 기반으로 UI를 업데이트하는 선언적 방식을 따르지만, 때로는 특정 요소에 직접적으로 접근하여 조작해야 하는 상황이 있을 수 있습니다. 이때 Template Refs가 유용합니다.

사용법

  • ref 속성으로 참조: Vue에서 ref 속성을 사용해 DOM 요소나 자식 컴포넌트에 대한 참조를 설정할 수 있습니다.
  • this.$refs로 접근: 설정한 ref는 Vue 인스턴스 내부에서 this.$refs를 통해 접근할 수 있습니다. Vue 3에서는 setup 함수 안에서 ref로 선언한 변수를 통해 참조할 수 있습니다.
<template>
  <div>
    <input ref="inputElement" type="text" />
    <button @click="focusInput">Focus Input</button>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  setup() {
    // inputElement에 대한 참조를 설정
    const inputElement = ref(null);

    const focusInput = () => {
      // DOM 요소에 접근
      inputElement.value.focus();
    };

    return {
      inputElement,
      focusInput
    };
  }
};
</script>

위 예시 코드에서는 DOM 요소에 focus를 부여하는 방식으로 ref 속성이 사용되었습니다.

자식 컴포넌트 접근 예시

자식 컴포넌트

<template>
  <div>
    <p>Child Component</p>
  </div>
</template>

<script>
export default {
  methods: {
    sayHello() {
      console.log('Hello from Child Component!');
    }
  }
}
</script>

부모 컴포넌트

<template>
  <div>
    <ChildComponent ref="childComponent" />
    <button @click="callChildMethod">Call Child Method</button>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  methods: {
    callChildMethod() {
      // 자식 컴포넌트의 메소드 호출
      this.$refs.childComponent.sayHello();
    }
  }
}
</script>

0개의 댓글