template ref
태그 같은 DOM element요소를 ref를 이용하여 접근하자

templateRef

기본

<script setup>
  const inputRef = ref(null);
  console.log('setup이후의 ref:', inputRef.value);//null
  onMounted(()=>{
    inputRef.value.value = 'hello ref'
    console.log('마운트이후의 ref:', inputRef.value);
</script>


<template>
  <div>
    <input ref="inputRef" type="text" />
    <p>
      {{ inputRef }}
    </p>
    <!--mounted가 되어야만 출력가능하기때문에 에러
    <p>
      {{ inputRef.value }}
    </p>
    -->
    <p v-if="inputRef">
      {{ inputRef.value }}
    </p>
    <p>
      {{ inputRef === $refs.inputRef }} 
    </p>
      
  </div>
</template>

image image



for을 통한 ref

<script setup>
  import { ref, onMounted } from 'vue'
  const arrayRefs = ref([]);
  const fruits = ref(['사과', '딸기', '포도']);
  onMounted(()=>{
    arrayRefs.value.forEach(item => console.log('item1: ', item.textContent));
    
    arrayRefs.value.forEach(item => console.log('item: ', item));
  })
</script>


<template>
  <div>
    <ul>
      <li
          v-for="fruit in fruits"
          :key="fruit"
          ref="arrayRefs">변수이용: {{ fruit }}</li>
    </ul>
    <ul>
      <li
          v-for="fruit in fruits"
          :key="fruit"
          ref="element => arrayRefs.push(element.textContent)">함수 이용: {{ fruit }}</li>
    </ul>
  </div>
</template>

image image



자식, 부모Component에서의 ref

권장하지않음(props를 사용하자.)

<script setup>에서는 expose를 따로 설정해줘야한다

자식Component

<template>
  <div>
    
    {{ $parent }} <!--부모접근가능-->
    
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  const message = ref('Hello Im Child');
  const say = () =>{
    console.log(message.value);
  }

  defineExpose({
    message,
    say,
  })
</script>

부모Component

<script setup>
  import { ref, onMounted } from 'vue'
    import TemplateChildRefs from './TemplateChildRefs.vue'
  const child = ref(null);
  onMounted(()=>{
    console.log('child.message', child.value.message);
    child.value.say();
  })

  const parentHi = 'hi';
  defineExpose({
    parentHi,
  })
</script>

<template>
  <TemplateChildRefs ref="child"></TemplateChildRefs>
</template>

참고자료: Vue3 완벽 마스터: 기초부터 실전까지 - “기본편”

소스코드 바로확인하기

댓글 쓰기