跳至主要内容

[Vue] 進階API-Refs

TL;DR

可以使用Refs快速取出需要的DOM元素

參考資料

相關連結


Codepen playground

<div id="app">
<div class="p-5">
<h3>使用 ref 定義元素</h3>
<input type="text" ref="inputDOM">

<h3 class="mt-5">使用 ref 取得元件內的資訊</h3>
<button type="button" @click="getComponentInfo">取得元件資訊</button>
<card ref="card"></card>

<h3 class="mt-5">進階,使用 ref 搭配 Bootstrap</h3>
<!-- 綁定開啟modal事件的按鈕本身 -->
<button @click="openModal">開啟 Bootstrap Modal</button>
<!-- modal本體開始(使用ref去快速讓按鈕指定該DOM元素) -->
<div class="modal" tabindex="-1" ref="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<!-- modal本體結束 -->
</div>
</div>

使用方法

直接在需要指定的標籤上加上ref="refName"

refName可以自訂,在取用時可以使用this.$refs.refName取到剛剛所指定refName的標籤

e.g: <input type="text" ref="inputDOM">

$refs取得DOM的時機

因為在created生命週期中,資料尚未準備好,所以無法取得我們剛剛透過ref去註冊的DOM元素。

需要等到mounted之後,才可以正確取用到。

元件的ref

如果在元件上使用ref,則可以在ㄜ$refs內完整取得該元件的所有內容(包含data資料等等) e.g:

<div id="app">
<button type="button" @click="getComponentInfo">取得元件資訊</button>
<card ref="card></card>
</div>

應用

開啟bootstrap元件

<div id="app">
<div class="p-5">
<h3 class="mt-5">進階,使用 ref 搭配 Bootstrap</h3>
<!-- click trigger method to open modal -->
<button @click="openModal">開啟 Bootstrap Modal</button>
<!-- modal start -->
<div class="modal" tabindex="-1" ref="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<!-- modal over -->
</div>
</div>