1) Refs 접근하기
Composition API로 참조를 얻으려면 동일한 이름의 참조를 선언해야 합니다.
- 컴포넌트가 마운트된 후에 접근할 수 있습니다.
- <template> 안에서 input으로 Refs참조에 접근하려는 경우 렌더링되기 전에는 참조가 null일 수 있습니다.
- <template> 안에서 $refs 내장 객체로 Refs 참조에 접근할 수 있습니다.
<template>
<input ref="input" type="text" />
<div>{{ input }}</div>
<div>{{ $refs.input }}</div>
<div>{{ input === $refs.input }}</div>
</template>
<script>
import { onMounted, ref } from 'vue';
export default {
components: {},
setup() {
const input = ref(null);
onMounted(() => {
input.value.value = 'Hello World!';
input.value.focus();
});
return {
input,
};
},
};
</script>
2) v-for 내부 참조
v3.2.25 이상에서 동작합니다.
v-for내부에서 ref가 사용될 때 ref는 마운트 후 요소 배열로 채워집니다.
<script>
import { ref, onMounted } from 'vue'
export default {
setup() {
const list = ref([1, 2, 3])
const itemRefs = ref([])
onMounted(() => console.log(itemRefs.value))
return {
list,
itemRefs
}
}
}
</script>
<template>
<ul>
<li v-for="item in list" ref="itemRefs">
{{ item }}
</li>
</ul>
</template>
3) Function Refs
ref속성에 문자열 키 대신 함수를 바인딩할 수도 있습니다.
<input :ref="(el) => { /* assign el to a property or ref */ }">
4) 컴포넌트 Refs
ref를 자식 컴포넌트에도 사용할 수 있습니다. ref로 자식 컴포넌트에 참조값을 얻게 되면 자식 컴포넌트의 모든 속성과 메서드에 대한 전체를 접근할 수 있습니다.
이러한 경우 부모/자식 컴포넌트간 의존도가 생기기 때문에 이러한 방법은 반드시 필요한 경우에만 사용해야 합니다. 그리고 일반적으로 ref 보다 표준 props를 사용하여 부모/자식간 상호작용을 구현해야 합니다.
자식 컴포넌트를 정의해 보겠습니다.
// Child.vue
<template>
<div>Child Component</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const message = ref('Hello Child!');
const sayHello = () => {
alert(message.value);
};
return {
message,
sayHello,
};
},
};
</script>
부모 컴포넌트에서 자식 컴포넌트의 상태나 메서드에 접근할 수 있습니다.
// Child.vue
<template>
<button @click="child.sayHello()">child.sayHello()</button>
<Child ref="child"></Child>
</template>
<script>
import { onMounted, ref } from 'vue';
import Child from './components/templateRefs/Child.vue';
export default {
components: {
Child,
},
setup() {
const child = ref(null);
onMounted(() => {
console.log(child.value.message);
});
return { child };
},
};
</script>
5) $parent
자식 컴포넌트에서 상위 컴포넌트 참조하기 위해서는 $parent 내장객체를 사용할 수 있습니다.
<template>
<div>Child Component</div>
<div>{{ $parent.message }}</div>
</template>
'개발이 좋아서 > Vue가 좋아서' 카테고리의 다른 글
20장 [VueRouter] VueRouter란? (0) | 2023.09.19 |
---|---|
19장 script setup 속성 (0) | 2023.09.15 |
17장 Provide / Inject (0) | 2023.09.14 |
16장 Slots (0) | 2023.09.14 |
15장 Non-Prop 속성 (fallthrough 속성) (0) | 2023.09.14 |