vue3 在父層取得子組件的 ref DOM屬性
我們在下面上要取得某 DOM 元素的時候,會先宣告一個 ref
常數,然後在元素的 html 上面加上 ref
屬性。
像是這樣:
<div class="modal fade" ref="modalRef">
//...
</div>
然後在 script
中:
import { ref } from "vue";
//...
const modalRef = ref();
setup() {
return { modalRef }
}
但是這時候我想把整個 modal
包成一個組件:
<template>
<div class="modal fade">
// ... 內容
</div>
</template>
<script>
export default {
name: "Modal",
setup() {
// ...
}
}
</script>
然後在父層引用這個組件:
<template>
<Modal ref="modalRef"/>
</template>
<script>
import Modal from "./Modal";
import { ref } from "vue";
export default {
components: { Modal },
setup() {
const modalRef = ref();
return { modalRef };
}
}
</script>
但這樣綁定的 ref
其實是錯誤的,vue 會找不到這個節點;所以我們不能直接綁在 component
身上,必須要傳到 component
裡面。
所以我們來改寫一下父組件
<template>
<Modal />
</template>
<script>
import Modal from "./Modal";
import { ref, provide } from "vue";
export default {
components: { Modal },
setup() {
const modalRef = ref();
provide("ref", modalRef)
return { };
}
}
</script>
使用 provide
傳遞出來之後,在子組件用 inject
接收。
<template>
<div class="modal fade" ref="modalRef">
// ... 內容
</div>
</template>
<script>
import { inject } from "vue";
export default {
name: "Modal",
setup() {
const modalRef = inject("ref");
return { modalRef }
}
}
</script>
0
發表評論
想要加入討論嗎?請盡情發表您的想法!